【问题标题】:confused about uicontrol's nextresponder对 uicontrol 的 nextresponder 感到困惑
【发布时间】:2019-01-29 07:57:15
【问题描述】:

如果您将 UIView 添加为 UIViewControler 的视图的子视图,并且不向 UIView 添加事件。 UIViewControler 的方法 like 将被调用。但是如果你添加一个 UIView 作为 UIButton 的子视图,并且不向 UIView 添加事件,按钮点击事件将不会被调用。所以它让我很困惑。当您将按钮添加为 UIView 的子视图时也会发生这种情况,按钮没有添加目标操作方法,它的 superview(UIView) 也没有调用方法。

【问题讨论】:

    标签: ios first-responder


    【解决方案1】:

    假设您的问题是这样的:为什么点击UIButton 不会让UIViewController 视图的touchesBegan 方法被调用?

    让我们看一下这个实验项目,为了简单起见,我使用了框架而不是约束。

    import UIKit
    
    class MyButton: UIButton {
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            super.touchesBegan(touches, with: event)
            print("BUTTON TOUCHES BEGAN")
        }
    }
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
    
            self.view.backgroundColor = .white
    
            let view1 = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
            view1.backgroundColor = .black
            self.view.addSubview(view1)
    
            let button = MyButton(type: .custom)
            button.frame = CGRect(x: 200, y: 100, width: 100, height: 100)
            button.setTitle("XXX", for: .normal)
            button.backgroundColor = .yellow
            button.setTitleColor(.black, for: .normal)
            button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)
            self.view.addSubview(button)
    
            let view2 = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
            view2.backgroundColor = .red
            button.addSubview(view2)
    
        }
    
        @objc func buttonClicked() {
            print("buttonClccked")
        }
    
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            super.touchesBegan(touches, with: event)
    
            print("TOUCHES BEGAN")
        }
    }
    

    你提到的每一个案例我都做过。

    view1 是普通视图。将其添加为控制器视图的子视图,然后点击它会触发控制器中的touchesBegan。这很好。

    view2 被添加为按钮的子视图,无论是否占用按钮的整个框架,然后您点击view2,按钮的touchesBegan 将被触发而不是控制器的。添加

    这些事情发生是因为当您点击按钮时,按钮的点击优先于控制器的视图,因为从按钮开始的每次触摸都被计为点击。

    【讨论】:

    • 感谢您的回答。这对我帮助很大。
    • 很高兴为您提供帮助,欢迎来到 Stack Overflow。如果此答案或任何其他答案解决了您的问题,请将其标记为已接受;)
    猜你喜欢
    • 1970-01-01
    • 2019-09-13
    • 2012-07-22
    • 2013-05-13
    • 2020-04-16
    • 2023-03-08
    • 2019-08-04
    • 2019-12-30
    • 2022-01-20
    相关资源
    最近更新 更多