Swift 4中touchesBegan失效:自定义UIView无法响应触摸事件
Hey there! Let’s work through why your custom SelectionView isn’t triggering those touch methods—this is a super common gotcha in UIKit, so I’ve got a few key things to check:
Common Causes & Fixes
1. Ensure isUserInteractionEnabled is Enabled
Even though UIView defaults this property to true, it’s easy to accidentally disable it (either in code or Interface Builder). Double-check:
- In code, add this to your
SelectionView’s initializers:override init(frame: CGRect) { super.init(frame: frame) self.isUserInteractionEnabled = true } required init?(coder: NSCoder) { super.init(coder: coder) self.isUserInteractionEnabled = true } - In Storyboard/XIB: Select your
SelectionView, go to the Attributes Inspector, and make sure "User Interaction Enabled" is checked.
2. Check for Overlapping Subviews
If there’s another view sitting on top of your SelectionView (and that top view has isUserInteractionEnabled = true), it’ll steal all the touch events. Either:
- Remove or reorder the overlapping view so it’s behind your
SelectionView - Set the overlapping view’s
isUserInteractionEnabled = falseif it doesn’t need to respond to touches.
3. Verify View Visibility & Alpha
UIKit ignores touch events for views that are:
isHidden = truealpha < 0.01
Make sure yourSelectionViewis visible and has an alpha value of at least 0.01 (most cases you’ll wantalpha = 1.0).
4. Check for Custom Hit-Test Overrides
If your SelectionView (or any of its parent views) overrides hitTest(_:with:) or point(inside:with:), a bug in that code might be preventing touches from reaching your view. For example, if point(inside:with:) returns false when it should return true, your view won’t get the touch event. Review those methods to ensure they’re correctly implemented.
5. Validate View Frame/Position
Sometimes your SelectionView might have a zero frame, or be positioned off-screen—so you think you’re touching it, but you’re not. Add a quick debug check in your view controller’s viewDidAppear(_:):
override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) print("SelectionView frame: \(selectionView.frame)") }
You can also add a background color to SelectionView to visually confirm its position:
override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.red.withAlphaComponent(0.5) // Visible debug color }
Give these fixes a try—chances are one of them will get your touch events firing again!
内容的提问来源于stack exchange,提问作者Parv Bhasker

