swift - 无法将现有方法附加到 UIButton

标签 swift

我正在尝试制作一个模拟应用程序,但我似乎无法让 UIButton 连接到我单击它时应执行的操作。 我不确定为什么它找不到方法,名称是相同的并且将 (_:) 添加到 #selector 什么都不做。

import UIKit

class LoginViewController: UIViewController {

    var loginButton: UIButton?

    @objc func onLoginButtonPress(sender: UIButton!) {
        print("Login Button Press")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setup()
    }

    func setup() -> Void {

        initLoginButton()
        self.view.backgroundColor = .green
    }

    func initLoginButton() -> Void {
        let loginButtonBounds = CGRect(x: 100, y: 100, width: 250, height: 250)
        loginButton = UIButton(frame: loginButtonBounds)
        loginButton!.backgroundColor = .red
        loginButton!.setTitle("Login", for: .normal)
        loginButton!.addTarget(self, action: #selector("onLoginButtonPress"), for: .touchUpInside)
        self.view.addSubview(loginButton!)
    }

最佳答案

loginButton!.addTarget(self, action: #selector(onLoginButtonPress(sender:)), for: .touchUpInside)

编辑此行代码,这应该适合您。最好不要使用 force-unwrapping,所以避免使用它。

关于swift - 无法将现有方法附加到 UIButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56962997/

相关文章:

ios - 遇到这个警告该如何解决?

swift - 按属性对关系中的对象进行排序?

ios - Swift 版本 NativeScript

swift - 有没有办法访问当前语言使用的零?

swift - @selector() 在 Swift 中?

ios - 从 Swift 函数中的异步调用返回数据

ios - 将委托(delegate)加载到 UITableView 时获取 EXC_BAD_INSTRUCTION

swift - 打字时扩大 uitableview 单元格高度并避免键盘

ios - 使用 UIStepper 递增/递减预填充的 UITextField

swift - 如何在 Swift 上为堆栈声明 "if optional"