为什么UIButton会消耗触摸事件而UIControl不会

6
  • 我在一个表格视图单元格中有一些自定义按钮。
  • 这些按钮由另一个视图包含,该视图不占用整个单元格。
  • 我希望按钮始终响应点击(并消耗点击,以便同时不选择单元格)。
  • 我希望我的按钮容器视图消耗不在按钮本身上的点击(以便不选择单元格)。
  • 我希望单元格中除了我的按钮容器之外的任何地方都按照惯例选择单元格。

为此,我将手势识别器附加到了我的按钮容器视图上。

只要我的按钮是 UIButton(即点击按钮本身会在按钮上触发 TouchUpInside 事件,点击按钮容器内的任何其他位置都不会触发任何操作,而在单元格中点击按钮容器之外的任何位置都会导致选择单元格),那么这就达到了预期效果。然而,如果我使用 UIControl 而不是 UIButton,那么情况就不同了——控件永远不会响应点击(按钮容器总是消耗点击,在按钮容器之外的任何位置点击,即在单元格中,都会导致选择单元格)。需要注意的是,如果我没有将手势识别器添加到我的按钮容器中,则控件的响应方式与 UIButton 相同。

唯一的解释是,UIButton(继承自 UIControl)在某种程度上添加了一些额外的触摸处理。在这种情况下,我想知道它做了什么以及我应该如何模拟它(我需要使用 UIControl 而不是 UIButton,因为我的按钮具有自定义视图层次结构,我不想在 UIButton 中进行操作)。

下面的视图控制器代码应该可以让任何人重现这个问题:

class ViewController: UITableViewController, UIGestureRecognizerDelegate {

    lazy var containerView: UIView = {
        let view: UIView = UIView()
        view.backgroundColor = UIColor.redColor()
        view.setTranslatesAutoresizingMaskIntoConstraints(false)
        view.addSubview(self.buttonContainerView)
        view.addConstraints([
            NSLayoutConstraint(item: self.buttonContainerView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.LeadingMargin, multiplier: 1.0, constant: 0.0),
            NSLayoutConstraint(item: self.buttonContainerView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.TrailingMargin, multiplier: 1.0, constant: 0.0),
            NSLayoutConstraint(item: self.buttonContainerView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.TopMargin, multiplier: 1.0, constant: 0.0),
            NSLayoutConstraint(item: self.buttonContainerView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.BottomMargin, multiplier: 1.0, constant: 0.0)
        ])

        return view
    }()

    lazy var buttonContainerView: UIView = {
        let view: UIView = UIView()
        view.backgroundColor = UIColor.blueColor()
        view.setTranslatesAutoresizingMaskIntoConstraints(false)
        view.addSubview(self.control)
        view.addSubview(self.button)
        view.addConstraints([
            NSLayoutConstraint(item: self.control, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 0.5, constant: 0.0),
            NSLayoutConstraint(item: self.control, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0),
            NSLayoutConstraint(item: self.button, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1.5, constant: 0.0),
            NSLayoutConstraint(item: self.button, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0.0)
        ])

        return view
    }()

    lazy var control: UIControl = {
        let view: UIControl = TestControl(frame: CGRectZero)
        view.addTarget(self, action: Selector("controlTapped:"), forControlEvents: UIControlEvents.TouchUpInside)

        return view
    }()

    lazy var button: UIButton = {
        let view: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
        view.setTitle("Tap button", forState: UIControlState.Normal)
        view.setTranslatesAutoresizingMaskIntoConstraints(false)
        view.addTarget(self, action: Selector("buttonTapped:"), forControlEvents: UIControlEvents.TouchUpInside)

        return view
    }()

    func controlTapped(sender: UIControl) -> Void {
        println("Control tapped!")
    }

    func buttonTapped(sender: UIButton) -> Void {
        println("Button tapped!")
    }

    var recogniser: UITapGestureRecognizer?
    var blocker: UITapGestureRecognizer?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.rowHeight = 200.0

        self.containerView.layoutMargins = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0)

        let recogniser: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tappedContainer:"))
        recogniser.delegate = self
        self.recogniser = recogniser

        self.containerView.addGestureRecognizer(recogniser)

        let blocker: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tappedBlocker:"))
        blocker.delegate = self
        self.blocker = blocker

        self.buttonContainerView.addGestureRecognizer(blocker)
    }

    func tappedContainer(recogniser: UIGestureRecognizer) -> Void {
        println("Tapped container!")
    }

    func tappedBlocker(recogniser: UIGestureRecognizer) -> Void {
        println("Tapped blocker!")
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let identifier: String = "identifier"
        let cell: UITableViewCell
        if let queuedCell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(identifier) as? UITableViewCell {
            cell = queuedCell
        }
        else {
            cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: identifier)

            cell.contentView.layoutMargins = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0)
            cell.contentView.backgroundColor = UIColor.purpleColor()

            cell.contentView.addSubview(self.containerView)

            cell.contentView.addConstraints([
                NSLayoutConstraint(item: self.containerView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: cell.contentView, attribute: NSLayoutAttribute.LeadingMargin, multiplier: 1.0, constant: 0.0),
                NSLayoutConstraint(item: self.containerView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: cell.contentView, attribute: NSLayoutAttribute.TrailingMargin, multiplier: 1.0, constant: 0.0),
                NSLayoutConstraint(item: self.containerView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: cell.contentView, attribute: NSLayoutAttribute.TopMargin, multiplier: 1.0, constant: 0.0),
                NSLayoutConstraint(item: self.containerView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: cell.contentView, attribute: NSLayoutAttribute.BottomMargin, multiplier: 1.0, constant: 0.0)
            ])
        }

        return cell
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        println("selected cell")
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
}

class TestControl: UIControl {
    override init(frame: CGRect) {
        super.init(frame: frame)

        let view: UIControl = self

        let label: UILabel = UILabel()
        label.text = "Tap control"
        label.userInteractionEnabled = false

        view.layer.borderColor = UIColor.orangeColor().CGColor
        view.layer.borderWidth = 2.0
        view.setTranslatesAutoresizingMaskIntoConstraints(false)
        label.setTranslatesAutoresizingMaskIntoConstraints(false)

        view.addSubview(label)
        view.addConstraints([
            NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.TopMargin, multiplier: 1.0, constant: 5.0),
            NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0.0),
            NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.GreaterThanOrEqual, toItem: view, attribute: NSLayoutAttribute.LeadingMargin, multiplier: 1.0, constant: 0.0),
            NSLayoutConstraint(item: label, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.LessThanOrEqual, toItem: view, attribute: NSLayoutAttribute.BottomMargin, multiplier: 1.0, constant: 0.0)
        ])
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

编辑

明确一下,我不是在寻找一个“只是工作”的替代方案——我想了解这种差异是什么,以及我应该采取什么行动来模拟它,或者可能是另一种语义上正确的方式。

1个回答

6
我的唯一解释是,UIButton(继承自UIControl)在某种程度上添加了一些额外的触摸处理。
您是正确的,UIButton很特殊。我在回答一个相关问题related question时做了一些研究,按钮事件触发的原因在Event Handling Guide for iOS: Gesture Recognizers的“与其他用户界面控件交互”部分中提到:
在iOS 6.0及更高版本中,默认控制操作会防止重叠的手势识别器行为。例如,按钮的默认操作是单击。如果将单击手势识别器附加到按钮的父视图,并且用户点击按钮,则按钮的操作方法接收触摸事件而不是手势识别器。
然后列出了示例,单指单击UIButton就是其中之一。
阻止手势识别器的方法,就像默认控件所做的那样,是让 TestControl 覆盖 gestureRecognizerShouldBegin: 方法(参见 UIView Class Reference)。如果你想模仿 UIButton 的行为,你可以使用类似以下的代码:
override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
    if let tapGestureRecognizer = gestureRecognizer as? UITapGestureRecognizer {
        if tapGestureRecognizer.numberOfTapsRequired == 1 && tapGestureRecognizer.numberOfTouchesRequired == 1 {
            return false;
        }
    }
    return true;
}

感谢您的解释和链接 - 看起来苹果正在告诉我们 UIButton 是一个例外(却没有告诉我们如何实现类似的行为)。您提供的代码完美地运行了,但是我想了解为什么,并确保它不容易改变。UIControl 没有声明 UIGestureRecognizerDelegate 符合性,所以我是否有效地覆盖了一个隐藏的手势识别器的私有方法? - Rupert
1
@Rupert gestureRecognizerShouldBegin: 实际上是 UIView 上的一个方法(UIControl 继承自 UIView),因此没有任何隐藏或私有的 API 参与。我刚刚在 UIView Class Reference 中仔细查看了该方法的文档,并指出 UISlider 使用它来阻止某些滑动手势,因此这是处理这些情况的官方方式(我将更新我的答案以说明这一点)。 - cszucko
@cszucko 出于好奇,你最终是如何解决这个问题的? - SwiftArchitect
@SwiftArchitect,我自己没有遇到过这种具体情况,但既然Rupert说我包含的代码片段有效,我可能会选择使用它。 - cszucko
当然,在答案下面发表了评论!我会删除我的愚蠢问题和这个评论... - SwiftArchitect

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接