无法将目标添加到 UIButton
Unable to add target to UIButton
我有一个以编程方式创建的 UIButton
。我给它添加了一个目标,但它似乎不正确 运行。这是我的代码(这是 UIView
的自定义 class):
override init(frame: CGRect) {
super.init(frame: frame)
print("targets:")
print(clickButton.allTargets())
clickButton.addTarget(self, action: #selector(self.clickPicture), for: .touchUpInside)
print("targets:")
print(clickButton.allTargets())
}
这是打印的结果:
如您所见,将目标添加到我的按钮并没有什么不同。这是 clickPicture
函数:
func clickPicture() {
print("clickpicture")
}
同样,这不会打印。有谁知道如何解决这个错误?谢谢!
编辑:
clickButton
的定义(在我的习惯 class 中):
var clickButton = UIButton()
init
中定义的其他属性:
clickButton.frame.size = CGSize(width: 100, height: 100)
clickButton.layer.cornerRadius = clickButton.frame.size.width / 2
clickButton.layer.borderColor = UIColor.white().cgColor
clickButton.layer.borderWidth = 2.5
clickButton.layer.backgroundColor = shadeColor.cgColor
clickButton.center.x = self.center.x
clickButton.center.y = self.frame.size.height - clickButton.frame.size.height// + 40
clickButton.addTarget(self, action: #selector(self.clickPicture), for: .touchUpInside)
self.addSubview(clickButton)
您必须更改此行
clickButton.addTarget(self, action: #selector(self.clickPicture), for: .touchUpInside)
至此
clickButton.addTarget(self, action: #selector(YourClassName.clickPicture), forControlEvents: UIControlEvents.TouchUpInside)
方法应该是
func clickPicture() {
print("clickpicture")
}
当我实例化它时,该按钮不在自定义视图的顶部。我改变了它的位置,它工作得很好。
我有一个以编程方式创建的 UIButton
。我给它添加了一个目标,但它似乎不正确 运行。这是我的代码(这是 UIView
的自定义 class):
override init(frame: CGRect) {
super.init(frame: frame)
print("targets:")
print(clickButton.allTargets())
clickButton.addTarget(self, action: #selector(self.clickPicture), for: .touchUpInside)
print("targets:")
print(clickButton.allTargets())
}
这是打印的结果:
如您所见,将目标添加到我的按钮并没有什么不同。这是 clickPicture
函数:
func clickPicture() {
print("clickpicture")
}
同样,这不会打印。有谁知道如何解决这个错误?谢谢!
编辑:
clickButton
的定义(在我的习惯 class 中):
var clickButton = UIButton()
init
中定义的其他属性:
clickButton.frame.size = CGSize(width: 100, height: 100)
clickButton.layer.cornerRadius = clickButton.frame.size.width / 2
clickButton.layer.borderColor = UIColor.white().cgColor
clickButton.layer.borderWidth = 2.5
clickButton.layer.backgroundColor = shadeColor.cgColor
clickButton.center.x = self.center.x
clickButton.center.y = self.frame.size.height - clickButton.frame.size.height// + 40
clickButton.addTarget(self, action: #selector(self.clickPicture), for: .touchUpInside)
self.addSubview(clickButton)
您必须更改此行
clickButton.addTarget(self, action: #selector(self.clickPicture), for: .touchUpInside)
至此
clickButton.addTarget(self, action: #selector(YourClassName.clickPicture), forControlEvents: UIControlEvents.TouchUpInside)
方法应该是
func clickPicture() {
print("clickpicture")
}
当我实例化它时,该按钮不在自定义视图的顶部。我改变了它的位置,它工作得很好。