坚持以编程方式在swift 3中添加目标到按钮

use*_*159 16 uibutton ios swift swift3

我使用Swift 3创建了一个UIButton,我希望它在按下时打印一些消息.

所以我做了类似这样的事情:在loadView()中

button.addTarget(self, action: #selector(ViewController.pressButton(button:)), for: .touchUpInside)
Run Code Online (Sandbox Code Playgroud)

一个方法:

func pressButton(button: UIButton) {

    NSLog("pressed!")

}
Run Code Online (Sandbox Code Playgroud)

但是当我点击按钮时没有任何反应.

Ras*_*n L 28

在您的按钮代码中添加viewDidLoad,它将适合您:

override func viewDidLoad() {
    super.viewDidLoad()
    let button = UIButton(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
    button.backgroundColor = UIColor.gray
    button.addTarget(self, action: #selector(pressButton(button:)), for: .touchUpInside)
    self.view.addSubview(button)
}

func pressButton(button: UIButton) {
    NSLog("pressed!")
}
Run Code Online (Sandbox Code Playgroud)

你鸵鸟政策需要添加ViewController.pressButtonselector,it's足够用function name.

Swift 4.x版本:

let button = UIButton(frame: CGRect(x: 10, y: 10, width: 100, height: 100))
button.backgroundColor = .gray
button.tag = 0
button.addTarget(self, action: #selector(pressButton(_:)), for: .touchUpInside)
self.view.addSubview(button)

@objc func pressButton(_ button: UIButton) {
    print("Button with tag: \(button.tag) clicked!")
}
Run Code Online (Sandbox Code Playgroud)


小智 6

在Swift3中尝试这个!

button.addTarget(self, action: #selector(self.pressButton(button:)), for: .touchUpInside)

@objc func pressButton(button: UIButton) { NSLog("pressed!") }
Run Code Online (Sandbox Code Playgroud)


ara*_*_86 5

使用以下代码.

button.addTarget(self, action: #selector(FirstViewController.cartButtonHandler), for: .touchUpInside)
Run Code Online (Sandbox Code Playgroud)

您的类名对应于FirstViewController

您的选择器对应于以下功能

func cartButtonHandler() {

}
Run Code Online (Sandbox Code Playgroud)


BHe*_*cks 0

您提到通话addTarget是在loadView(). 这是在您的某种自定义子视图中还是在 viewController 中?

从您的选择器来看,它的目标是您的ViewController类中的一个方法,但如果target此操作的对象是视图本身,那么该操作不会执行是有道理的。

如果您在 viewController 中声明按钮,并按viewDidLoad上述方式添加此目标,则应按照您的要求打印消息。我相信你的行动“针对”了错误的阶级。