我有一个容器,clipToBounds
设置为false,视图超出其范围。越界视图无法识别触摸事件。
答案 0 :(得分:4)
只需将此课程添加到您的视图
即可class MyView: UIView {
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
for subview in subviews as [UIView] {
if !subview.isHidden
&& subview.alpha > 0
&& subview.isUserInteractionEnabled
&& subview.point(inside: convert(point, to: subview), with: event) {
return true
}
}
return false
}
}
答案 1 :(得分:-1)
这是一个扩展程序,可让您在容器中触摸剪切的子视图。将此文件粘贴到项目中并设置containerView.allowTouchesOfViewsOutsideBounds = true
public extension UIView {
private struct ExtendedTouchAssociatedKey {
static var outsideOfBounds = "viewExtensionAllowTouchesOutsideOfBounds"
}
/// This propery is set on the parent of the view that first clips the content you want to be touchable
/// outside of the bounds
var allowTouchesOfViewsOutsideBounds:Bool {
get {
return objc_getAssociatedObject(self, &ExtendedTouchAssociatedKey.outsideOfBounds) as? Bool ?? false
}
set {
UIView.swizzlePointInsideIfNeeded()
subviews.forEach({$0.allowTouchesOfViewsOutsideBounds = newValue})
objc_setAssociatedObject(self, &ExtendedTouchAssociatedKey.outsideOfBounds, newValue, .OBJC_ASSOCIATION_RETAIN)
}
}
func hasSubview(at point:CGPoint) -> Bool {
if subviews.count == 0 {
return self.bounds.contains(point)
}
return subviews.contains(where: { (subview) -> Bool in
let converted = self.convert(point, to: subview)
return subview.hasSubview(at: converted)
})
}
static private var swizzledMethods:Bool = false
@objc func _point(inside point: CGPoint, with event: UIEvent?) -> Bool {
if allowTouchesOfViewsOutsideBounds {
return _point(inside:point,with:event) || hasSubview(at: point)
}
return _point(inside:point,with:event)
}
static private func swizzlePointInsideIfNeeded() {
if swizzledMethods {
return
}
swizzledMethods = true
let aClass: AnyClass! = UIView.self
let originalSelector = #selector(point(inside:with:))
let swizzledSelector = #selector(_point(inside:with:))
swizzle(forClass: aClass, originalSelector: originalSelector, swizzledSelector: swizzledSelector)
}
}