Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why am I getting this warning when I add the target to my UIButton in my controller? (the warning and code is stated below)

I am programmatically creating a button and am receiving this warning for every button I create when I add the "button.addTarget" line of code to it. The code is below:

let logoutButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Log Out", for: .normal)
        button.setWidth(width: 100)
        button.setHeight(height: 30)
        button.layer.cornerRadius = 15
        button.backgroundColor = .white
        button.setTitleColor(.red, for: .normal)
        button.addTarget(self, action: #selector(handleLogOut), for: .touchUpInside)
        return button
    }()

The warning I am getting for this is:
‘self’ refers to the method ‘HomeController.self’, which may be unexpected

And it also comes with a fix, which is:
Use ‘HomeController’ to silence this warning

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, when I implement this fix, the "self" in the first parameter of the "button.addTarget" line becomes "HomeController.self" and makes the app crash.

I always used to use "self" for this and it never gave warnings until recently. Now it gives a warning for this every time. When I use "self," it all still works fine, but the warnings in Xcode are annoying… any help is appreciated.

>Solution :

Use lazy var instead of let it will solve problem or set target in viewDidLoad.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading