以编程方式快速添加按钮

时间:2020-06-04 18:37:55

标签: ios swift uibutton addtarget

我试图以编程方式添加按钮,我创建了按钮,该按钮在应用程序中显示,但是问题是当我在.addTarget中写入#selector时发生错误(成功构建,但操作无效)我试图写playAction()playAction(sender:)playAction。他们都不工作。 enter image description here

playPauseButton.addTarget(self, action: #selector(playAction(sender:)), for: .touchUpInside)

@objc
func playAction(sender: UIButton){
    print("Hello")
}

UPD:我通过仅创建系统按钮并对其进行更改来解决。也许我的Xcode有错误,并且因此发生错误。

2 个答案:

答案 0 :(得分:0)

您的函数需要具有@objc属性。这样就可以将其作为选择器进行查找。

@objc
func playAction(sender: UIButton) {
      print("Hello")
}

答案 1 :(得分:0)

更改为

playPauseButton.addTarget(self, action: #selector(playAction), for: .touchUpInside)

没关系:

@objc
func playAction(sender: UIButton) {
      print("Hello")
}

为我工作