I began to learn Swift recently. When I tried to make my first App
I got confused with UIBarButtonItem
. If I put let UIBarButtonItem
initialization outside the viewDidLoad()
function, nothing happens when I press the Next Button.
class ViewController: UIViewController, UITextFieldDelegate {
let rightBarButton: UIBarButtonItem = UIBarButtonItem(title: "Next", style: .plain, target: self, action: #selector(onClickNext(button:)))
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
self.navigationItem.rightBarButtonItem = rightBarButton
}
func onClickNext(button: UIBarButtonItem) {
print("should push view controller")
}
}
However, when I put the initialization
into the viewDidLoad()
function, the output area does output the sentense that I set in the onClickNext(button:)
function.
class ViewController: UIViewController, UITextFieldDelegate {
var rightBarButton: UIBarButtonItem?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
self.rightBarButton = UIBarButtonItem(title: "Next", style: .plain, target: self, action: #selector(onClickNext(button:)))
self.navigationItem.rightBarButtonItem = rightBarButton
}
func onClickNext(button: UIBarButtonItem) {
print("should push view controller")
}
}
Also, I I found that when I put the initialization
outside the viewDidLoad()
function, and I add a UITextField
to viewController
, the rightBarButton
works if I touch the textfield
before I press the button.
That make me confused. What is the mechanism?