2

按钮是在情节提要中创建的,我想添加一个动作。

self.cancel.action = NSSelectorFromString("cancel:")

func cancel(sender: UIBarButtonItem) ->() {
}

这不起作用。谢谢

4

4 回答 4

8

只需在您的 swift 类中创建一个函数,如下所示

@IBAction func cancel() {
   // your code
}

并通过从按钮到视图控制器的 ctrl 拖动将其连接到情节提要中。

于 2014-08-31T09:51:22.963 回答
2

见我的。

  1. 将 UIButton 添加到 UIBarbuttonitem。

    self.navigationController?.navigationBarHidden = false
    
    //making a button
    var button: UIButton = UIButton()
    button.setImage(UIImage(named: "person-icon.jpg"), forState: .Normal)
    button.frame = CGRectMake(0, 0, 25, 25)
    button.targetForAction("actioncall", withSender: self)
    button.addTarget(self, action: "actioncall", forControlEvents: UIControlEvents.TouchUpInside)
    
    //making a UIBarbuttonItem on UINavigationBar
    var rightItem:UIBarButtonItem = UIBarButtonItem()
    rightItem.customView = button        
    self.navigationItem.rightBarButtonItem = rightItem
    
  2. 初始化一个 UIBarButtonItem

    let rightNavItem = UIBarButtonItem(image: UIImage(named: "search1x"), landscapeImagePhone: nil, style: UIBarButtonItemStyle.Plain, target: self, action: "actioncall")
    navigationItem.rightBarButtonItem = rightNavItem
    
  3. 或者

    let rightNavItem = UIBarButtonItem()
    rightNavItem.action = "action call"
    
    
    //Anticipated Method on clicking uibarbuttonitem
    func actioncall(){
    }
    
于 2015-09-01T06:12:24.140 回答
0
@IBAction func action() {
   // your code
}       

   var button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
   button.frame = CGRectMake(100, 100, 100, 50)
   button.backgroundColor = UIColor.greenColor()
   button.setTitle("Button", forState: UIControlState.Normal)
   button.addTarget(self, action: "action", forControlEvents: UIControlEvents.TouchUpInside)
   self.view.addSubview(button)
于 2016-06-03T09:15:58.423 回答
0

或者如果选择器在不同的类中

let barBtn = UIBarButtonItem(title: nil, style: UIBarButtonItemStyle.Plain, target: self, action: #selector(CustomToolbarItemsClass.testSelector))


//This is in CustomToolbarItemsClass class
@objc static func testSelector(){
 print("Hello!")
}
于 2016-07-20T18:29:11.283 回答