ios - 按钮触摸事件

标签 ios swift button swift3 touch

请检查以下代码。 我在 mainView 上制作了按钮。 但是按钮不会调用“thumbsUpButtonPressed”方法。 请检查!

override func viewDidLoad() {
    super.viewDidLoad()

    let button = UIButton(type: .custom)
    button.frame = CGRect(x: 60, y: 100, width: 50, height: 50)

    button.backgroundColor = .red //.clear
    button.layer.cornerRadius = 5
    button.layer.borderWidth = 1
    button.layer.borderColor = UIColor.black.cgColor

    button.clipsToBounds = true
    //button.setImage(UIImage(named:"thumbsUp.png"), for: .normal)
    button.addTarget(self, action: #selector(thumbsUpButtonPressed), for: .touchDown)

    view.addSubview(button)
}

func thumbsUpButtonPressed(sender: UIButton) {
    print("thumbs up button pressed")
}

最佳答案

如果您想将按钮作为参数传递,您必须在选择器中指定它。为此,您可以在方法名称后添加 (_:)

尝试:

button.addTarget(self, action: #selector(thumbsUpButtonPressed(_:)), for: .touchDown)

如果您希望它与您现有的代码一起工作,您需要更改您的方法以不接受按钮作为参数,如下所示:

func thumbsUpButtonPressed() {
    print("thumbs up button pressed")
}

关于ios - 按钮触摸事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41788348/

相关文章:

objective-c - willRotateToInterfaceOrientation 在 Universal MasterDetail 应用程序中不起作用

ios - 'FIRAppNotConfigured',原因 : 'Failed to get default Firebase Database instance. Must call ` [FIRApp configure ]` (` FirebaseApp. configure()`(Swift 中)

ios - 如何在 swift 中创建 base 64 数据

java - 井字游戏按钮按下创建 AND 键调度超时

ios - 将自定义 UIBarButtonItem 添加到 UINavigationBar

ios - 在我拥有的两个 iOS 应用程序之间共享文件/数据

ios - 单击搜索栏时降低行高

ios - UIWebView 内存泄漏。释放未使用资源的魔法是什么?

swift - 是否可以使用 SwiftUI 将键盘上的 "return"键更改为 "done"?

java - 图像不重叠按钮