[英]Why doesn't my addTarget's function on button work?
我正在實現一些要在點擊按鈕后調用的函數,但不會調用該函數的主體。 這是我的代碼,它演示了我需要做什么
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 ")
}
這就是我的 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 是我創建的一個函數,用於以編程方式設置視圖的約束
從您顯示的代碼中,最明顯的是您使用了let
在使用閉包樣式構建帶有動作的變量時,我一直認為您應該使用lazy var
變量實例化。 這是使用(我相信)因為self
在編譯時是未知的。
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 ")
}
lazy var
變量的使用是一個屬性,它的初始值直到第一次使用時才計算。 (來源)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.