按鈕是在故事板中創建的,我想添加一個動作。將動作添加到UIBarButtonItem Swift
self.cancel.action = NSSelectorFromString("cancel:")
func cancel(sender: UIBarButtonItem) ->() {
}
這不行。由於
按鈕是在故事板中創建的,我想添加一個動作。將動作添加到UIBarButtonItem Swift
self.cancel.action = NSSelectorFromString("cancel:")
func cancel(sender: UIBarButtonItem) ->() {
}
這不行。由於
看我的。
將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(){
}
就在您的SWIFT類中創建一個功能類似於下面
@IBAction func cancel() {
// your code
}
,並且被Ctrl拖動從按鈕到您的視圖控制器,它在故事板連接。
@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!")
}
歡迎來到SOF。確保你接受答案,如果它幫助你。 – Mundi 2014-08-31 09:52:51