【问题标题】:Why can't I interact with subviews?为什么我不能与子视图交互?
【发布时间】:2020-08-21 05:39:12
【问题描述】:

我有一个视图控制器,我可以在其中添加多个带有LongPressGesture 的子视图。对于每个subview,我提供了一个TapGesture,它应该为此视图打开一个popover(见下图)。

我的问题是,我只能打开我添加的最后一个子视图的弹出框。那么为什么我不能再与其他子视图交互了呢? 这是我在 Swift 中的第一个应用程序,所以如果有人可以帮助我,那就太好了。

一些代码给你:
这是创建新子视图的根视图控制器上的 LongPressGesture。

@IBAction func onLongPress(_ gesture : UILongPressGestureRecognizer) {

    let position: CGPoint = gesture.location(in: view)

    if(gesture.state == .began) {
        let subview = MySubview(position: position)
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
        subview.addGestureRecognizer(tapGesture)

        view.addSubview(subview)
    }
    else if (gesture.state == .ended) {
        let subview = self.view.subviews.last
        self.openContextMenu(for: subview)
    }
}

带有子视图的 ViewController:-

【问题讨论】:

    标签: ios swift xcode ipad


    【解决方案1】:

    好的,我找到了解决问题的方法。好消息是,它只检测子视图框架中的触摸。

    在我的根视图控制器中我添加了:

        var isPanGesture = false
    
        override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
            isPanGesture = true
    
            if let subview = touches.first!.view as? MySubview {
                let position = touches.first!.location(in: self.view)
                link.center = position
            }
        }
        override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
            if let subview = touches.first!.view as? MySubview {
                if(!isPanGesture) {
                    self.openContextMenu(for: subview)
                }
                isPanGesture = false
            }
        }
    

    【讨论】:

      【解决方案2】:

      当对事件做出反应(在您的情况下长按)时,只有第一响应者会处理该事件。将子视图添加到视图时,所有子视图都会一个接一个地添加。所以最后添加的子视图将处理事件 - 如果它正在监听事件。如果你需要一个特定的子视图来处理事件,你可以把它放在前面

      parentView.bringSubviewToFront(view: subView)
      

      或者,您也可以禁用其他子视图

      subView.isUserInteractionEnabled = false
      

      【讨论】:

      • 到目前为止谢谢,但我的问题是无论我点击哪个子视图,弹出框都应该出现在点击的视图旁边。这是否可能,或者层系统不是为该用例设计的?
      猜你喜欢
      • 2020-11-15
      • 2021-10-09
      • 2017-11-27
      • 2012-02-09
      • 2022-11-02
      • 2012-10-30
      • 1970-01-01
      • 2020-05-26
      • 1970-01-01
      相关资源
      最近更新 更多