按钮是在情节提要中创建的,我想添加一个动作。
self.cancel.action = NSSelectorFromString("cancel:")
func cancel(sender: UIBarButtonItem) ->() {
}
这不起作用。谢谢
按钮是在情节提要中创建的,我想添加一个动作。
self.cancel.action = NSSelectorFromString("cancel:")
func cancel(sender: UIBarButtonItem) ->() {
}
这不起作用。谢谢
只需在您的 swift 类中创建一个函数,如下所示
@IBAction func cancel() {
// your code
}
并通过从按钮到视图控制器的 ctrl 拖动将其连接到情节提要中。
见我的。
将 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
或者
let rightNavItem = UIBarButtonItem()
rightNavItem.action = "action call"
//Anticipated Method on clicking uibarbuttonitem
func actioncall(){
}
@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)
或者如果选择器在不同的类中
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!")
}