按钮是在故事板中创建的,我想添加一个动作。
self.cancel.action = NSSelectorFromString("cancel:")
func cancel(sender: UIBarButtonItem) ->() {
}
这不起作用。感谢
答案 0 :(得分:8)
只需在swift类中创建一个函数,如下所示
@IBAction func cancel() {
// your code
}
通过从按钮拖动到视图控制器,在故事板中连接它。
答案 1 :(得分:2)
见我的。
将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
初始化UIBarButtonItem
let rightNavItem = UIBarButtonItem(image: UIImage(named: "search1x"), landscapeImagePhone: nil, style: UIBarButtonItemStyle.Plain, target: self, action: "actioncall")
navigationItem.rightBarButtonItem = rightNavItem
OR
let rightNavItem = UIBarButtonItem()
rightNavItem.action = "action call"
//Anticipated Method on clicking uibarbuttonitem
func actioncall(){
}
答案 2 :(得分: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)
答案 3 :(得分: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!")
}