Swift 正确对齐以编程方式创建的 UIBarButtonItem

Swift properly aligns a UIBarButtonItem that was created programatically

我使用以下 以编程方式在 Swift 中创建了一个 UIBarButtonItem,但图标没有正确对齐到边框。这是按钮的代码。谁能告诉我如何修改下面的代码以正确对齐 UIBarButtonItem 图像?

第一个图像显示了以编程方式创建的 uibarbuttonitem 的位置,第二个图像显示了从故事板创建的 uibarbuttonitem。我希望以编程方式创建的 uibarbuttonitem 看起来像使用故事板创建的 uibarbuttonitem。感谢您的帮助!

var button: UIButton = UIButton()
button.setImage(UIImage(named: "leftArrow.png"), forState: .Normal)
button.frame = CGRectMake(0, 0, 40, 40)
button.targetForAction("actioncall:", withSender: nil)

var leftBarButtonItem:UIBarButtonItem = UIBarButtonItem()
leftBarButtonItem.customView = button
self.navigationItem.leftBarButtonItem = leftBarButtonItem 

此外,如何正确设置按下 uibarbuttontiem 时的动作?我尝试了以下但从未调用过。

func actioncall(sender: AnyObject){
    println("action")
}

编辑 1:感谢 agy 的回复,我将代码更新如下。

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(true)

   if (cond){

    var button: UIButton = UIButton()
    button.setImage(UIImage(named: "leftArrow.png"), forState: .Normal)
    button.frame = CGRectMake(0, 0, 40, 40)
    button.addTarget(self, action: "actioncall:", forControlEvents: .TouchUpInside)
    var leftBarButtonItem:UIBarButtonItem = UIBarButtonItem()
    leftBarButtonItem.customView = button

    var negativeSpacer:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
    negativeSpacer.width = -20; // set the value you need
    self.navigationItem.leftBarButtonItems  = [negativeSpacer,leftBarButtonItem]

   }
}

func actioncall(sender: UIButton!){
        println("action")
}

但操作仍然失败。当我按下 uibarbuttontiem 时应用程序崩溃,我收到以下错误消息

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[AppName.ProfileViewController actioncall:]: unrecognized selector sent to instance 0x7a07a470'

该操作的正确功能是什么?

编辑 2:动作调用与我创建 UIBarButtonItem 的位置相同 class。我在 viewwillappear 上设置了 leftbarbutton,因为根据查看此 viewcontroller 的人,返回的选项将替换位于 leftbarbutton 上的先前选项。

尝试添加一个负间隔符,并将方法 targetForAction 更改为 addTarget:

    var button: UIButton = UIButton()
    button.setImage(UIImage(named: "leftArrow.png"), forState: .Normal)
    button.frame = CGRectMake(0, 0, 40, 40)
    button.addTarget(self, action: "actioncall:", forControlEvents: .TouchUpInside)
    var leftBarButtonItem:UIBarButtonItem = UIBarButtonItem()
    leftBarButtonItem.customView = button

    var negativeSpacer:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: nil, action: nil)
    negativeSpacer.width = -5; // set the value you need
    self.navigationItem.leftBarButtonItems = [negativeSpacer,leftBarButtonItem]

func actioncall(sender: UIButton!){
    print("Called")
}