【问题标题】:Button touch Event按键触摸事件
【发布时间】:2017-06-06 21:36:23
【问题描述】:

请检查以下代码。 我在 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")
}

【问题讨论】:

  • 我试过你的代码,它打印出“按下了竖起大拇指的按钮”,我看不出有什么问题。你还有更多代码要展示吗?
  • 谢谢。但仅此而已。我制作了 5 个 TabView,它是第一个 TabView 上的代码。你认为这段代码在 TabView 上不起作用吗?

标签: ios swift button swift3 touch


【解决方案1】:

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

尝试:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 2013-07-27
    • 2022-12-11
    • 2017-09-13
    相关资源
    最近更新 更多