【问题标题】:Simple tvOS UIButton is not working简单的 tvOS UIButton 不起作用
【发布时间】:2015-12-16 20:12:38
【问题描述】:

我正在尝试实现一个简单的 UIButton(tvOS 和 Swift),但 TouchDown 事件没有触发。 (也尝试过 TouchUpInside)。

  • 在模拟器中,我可以直观地看到按钮被按下。

我的 ViewController.swift 代码是:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let button = UIButton(type: UIButtonType.System)
        button.frame = CGRectMake(100, 100, 400, 150)
        button.backgroundColor = UIColor.greenColor()
        button.setTitle("Test", forState: UIControlState.Normal)
        button.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchDown)

        self.view.addSubview(button)

        self.view.userInteractionEnabled = true    
    }

    func buttonAction(sender:UIButton!){
        NSLog("Clicked")
    }
}

我需要做什么才能检测到按钮点击?

【问题讨论】:

    标签: swift uibutton tvos


    【解决方案1】:

    您不应该在 tvOS 上使用“.TouchDown”或“.TouchUpInside”,因为这不会达到您的预期:您可能想改用“UIControlEvents.PrimaryActionTriggered”。

    TouchUpInside 是由实际触摸触发的,而实际情况并非如此。如果您希望按下遥控器上的 Select 按钮来触发您的按钮,您应该使用 PrimaryActionTriggered。

    【讨论】:

    • 这正是我想要的,效果很好!谢谢@Erez
    【解决方案2】:

    UIControl.Event.primaryActionTriggered 是 tvOS addTarget 方法所必需的:

    button.addTarget(self, action: #selector(ViewController.didTapAcctionButton(_:)), for: .primaryActionTriggered)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-11
      • 2021-05-18
      • 2018-11-14
      • 2017-05-19
      • 2013-03-21
      相关资源
      最近更新 更多