我正在实现一些函数,一旦按钮被点击就会被调用,但函数的主体不会被调用。下面是我的代码,它演示了我需要做的事情
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是我创建的一个函数,用于以编程方式设置视图的约束
发布于 2020-02-08 22:17:40
从您所展示的代码中,最明显的就是您对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
的使用是一个在第一次使用时才计算其初始值的属性。(Source)
https://stackoverflow.com/questions/60127494
复制相似问题