As you've discovered, it makes a big difference where this line occurs:
let barButton = UIBarButtonItem(image: #imageLiteral(resourceName: "settings"),
style: .plain, target: self, action: #selector(presentSettings))
The problem is the target:self
part. When the bar button item is configured as part of an instance property initializer (your first example), the instance doesn't exist yet — it is what we are initializing. So self
has no meaning, and the button ends up with no target
. Therefore, tapping the button does nothing.
(Actually, to be quite technical, self
is the class, but that's not a helpful thing to know.)
In your second example, that line is part of viewDidLoad
, which runs considerably after the view controller instance has come into existence and has been initialized. viewDidLoad
is an instance method, in fact. So self
is the instance, as you expect.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…