I'm having trouble getting a simple toolbar action to work - I've seen this question asked before, but the answers don't seem to work. All I've done so far is create a new test project (with Xcode 7.3) and modified the ViewController
class as follows:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
print("viewDidLoad")
let tb = UIToolbar()
let actionClear = #selector(ViewController.clearAction(_:))
let clearButton = UIBarButtonItem(barButtonSystemItem: .Trash, target: self, action: actionClear)
tb.items = [clearButton]
self.view.addSubview(tb)
tb.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activateConstraints([
tb.bottomAnchor.constraintEqualToAnchor(self.view.bottomAnchor),
tb.centerXAnchor.constraintEqualToAnchor(self.view.centerXAnchor)
])
}
func clearAction (sender: AnyObject) {
print("clear")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The code compiles w/o error, the trash can icon shows up at the bottom of the screen (testing on an iPad), but the action never gets executed when I touch the icon.
I saw some (old) answers that seemed to indicate that you need to use a custom view ( UIButton
) with a UIBarButtonItem
, but this seems a little crazy, since the purpose of a UIBarButtonItem
is to create an item for a toolbar. What am I missing here?
The problem here is not with your barButton its due to constraints. Add Width constraint to your toolbar:
NSLayoutConstraint.activateConstraints([
tb.bottomAnchor.constraintEqualToAnchor(self.view.bottomAnchor),
tb.centerXAnchor.constraintEqualToAnchor(self.view.centerXAnchor),
tb.widthAnchor.constraintEqualToConstant(self.view.bounds.width)
])
delete sender:AnyObject in the clearAction method then Try as you are using empty argument method in selector method
func clearAction () {
print("clear")
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.