简体   繁体   中英

Passing tap action from one view to another

I have two UIViews A and B. Both of these views are placed one on another. Suppose View A is placed above B. So when I tap on View A it is consuming all tap actions. But I dont want that action to be consumed till View A only. I want to get actions on View B where it was tapped.

All my view has userInteractionEnabled = true

class PassthroughView : UIView {
  override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? 
  {
    let view = super.hitTest(point, with: event)
    return view == self ? nil : view
  }

    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        print("Tap Called")
        return false
    }
}

I tried these codes after see some solutions but doesnt seems to be working.

Also View A has swipe gesture to work.

 _V_i_e_w_B___
|   ____
|  |View A
|  |
|  |
|  |
|  |
|__|__
   |_____

In UIView subclass override hitTest method only

class PassthroughView : UIView {
    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView?
    {
        let view = super.hitTest(point, with: event)
        return view == self ? nil : view
    }
}

And create view A with the subclass and another view B with UIView class.

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let b = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
        b.backgroundColor = .gray
        b.center = view.center
        view.addSubview(b)

        let a = PassthroughView(frame: CGRect(x: 0, y: 0, width: 275, height: 275))
        a.backgroundColor = .lightGray
        a.center = view.center
        view.addSubview(a)       
    }
}

每当将视图A放置在视图B上方时,将视图A的userInteractionEnabled更改为false,您的点击将被传递到视图B。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM