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

时间:2015-06-28 18:24:28

标签: ios swift uibarbuttonitem

我使用以下tutorial以编程方式在Swift中创建UIBarButtonItem,但图标未正确对齐边框。这是按钮的代码。任何人都可以告诉我如何修改下面的代码以正确对齐UIBarButtonItem图像?

第一张图片显示了以编程方式创建的uibarbuttonitem的位置,第二张图片显示了从storyboard创建的uibarbuttonitem。我希望以编程方式创建的uibarbuttonitem看起来像使用storyboard创建的uibarbuttonitem。谢谢你的帮助!

enter image description here enter image description here

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的类相同。我在viewwillappear上设置了leftbarbutton,因为根据谁查看此viewcontroller,返回的选项将替换位于leftbarbutton上的上一个选项。

1 个答案:

答案 0 :(得分:3)

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

    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")
}