(Swift) Handling the part of the subview beyond the parent view, still clickable

created at 11-14-2021 views: 3

1) Problem scenario

As shown in the figure below, the yellow view is the parent view, and the red is the child view.
By default, the red view exceeds the yellow view, and clicking is invalid;

example

2) solution

//Rewrite the following method in the parent view
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView?

3) Source code indication

override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
     let supView = super.hitTest(point, with: event)
     for subView in self.subviews {
         //Convert the parent point point to the point in the child coordinate system
         let convertedPoint = subView.convert(point, from: self)
         let targetView = subView.hitTest(convertedPoint, with: event)
         if targetView != nil {
             return targetView
         }
     }
     return supView
}
created at:11-14-2021
edited at: 11-14-2021: