简体   繁体   中英

Why doesn't my addTarget's function on button work?

I am implementing some function to be called once a button is tapped but the function's body doesn't get called. Here is my code which demonstrates what I need to do

let editProfileFollowButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Edit Profile", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
        button.layer.borderColor = UIColor.lightGray.cgColor
        button.layer.borderWidth = 1
        button.layer.cornerRadius = 3
        button.addTarget(self, action: #selector(handleEditProfileOrFollow), for: .touchUpInside)
        return button
    }()
    @objc func handleEditProfileOrFollow () {
        print("Execute edit profile or follow ")
    }

and this is what happens in my init

addSubview(editProfileFollowButton)
        editProfileFollowButton.setAnchor(top: postsLabel.bottomAnchor, left: postsLabel.leftAnchor, right: followingLabel.rightAnchor, bottom: nil, paddingBottom: 0, paddingLeft: 0, paddingRight: 0, paddingTop: 2, height: 34, width: 0)
    }

PS: setAnchor is a function that I created to set up the constraints of the view programmatically

From the code you have shown, the most obvious thing is your use of let

When building variables with actions using a closure style, I have always been under the impression that you should use a lazy var instantiation. This is used (I believe) as self is not known at compile time.

lazy var editProfileFollowButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("Edit Profile", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 14)
        button.layer.borderColor = UIColor.lightGray.cgColor
        button.layer.borderWidth = 1
        button.layer.cornerRadius = 3
        button.addTarget(self, action: #selector(handleEditProfileOrFollow), for: .touchUpInside)
        return button
    }()
    @objc func handleEditProfileOrFollow () {
        print("Execute edit profile or follow ")
    }

The use of lazy var is a property whose initial value is not calculated until the first time it is used. (Source )

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM