无法将目标添加到UIButton

时间:2016-08-07 21:04:39

标签: ios swift uibutton target

我有一个以编程方式创建的UIButton。我已经添加了一个目标,但它似乎没有正常运行。这是我的代码(这是UIView的自定义类):

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())

}

这就是打印结果:

enter image description here

如您所见,向我的按钮添加目标并没有什么不同。这是clickPicture函数:

func clickPicture() {

    print("clickpicture")

}

同样,这不会打印。有谁知道如何解决这个错误?谢谢!

编辑:

clickButton的定义(在我的自定义类中):

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)

2 个答案:

答案 0 :(得分:0)

当我实例化它时,该按钮不在自定义视图的顶部。我改变了立场,工作得很好。

答案 1 :(得分:-1)

你必须改变这一行

clickButton.addTarget(self, action: #selector(self.clickPicture), for: .touchUpInside)

到这个

clickButton.addTarget(self, action: #selector(YourClassName.clickPicture), forControlEvents: UIControlEvents.TouchUpInside)

方法应该是

func clickPicture() {

    print("clickpicture")

}