實際開發(fā)中萝喘,常常遇到一些超出父視圖的按鈕:
例如:
Snip20180327_2.png
這是后的做法是遍歷到響應(yīng)事件的視圖,將點擊的坐標轉(zhuǎn)化到父視圖,并返回相應(yīng)subView
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if (!self.isUserInteractionEnabled || self.isHidden || self.alpha <= 0.01 ){
return nil
}
let resultView = super.hitTest(point, with: event)
if resultView != nil {
return resultView
}else{
for subView in self.subviews.reversed() {
// 這里根據(jù)層級的不同,需要遍歷的次數(shù)可能不同脂矫,看需求來寫,我寫的例子是一層的
let convertPoint : CGPoint = subView.convert(point, from: self)
let hitView = subView.hitTest(convertPoint, with: event)
if (hitView != nil) {
return hitView
}
}
}
return nil
}
在讓超出父視圖的部分響應(yīng)點擊后霉晕,可能按鈕還是不好點擊庭再,原因是按鈕圖片太小, 所以要擴大按鈕響應(yīng)時間的范圍牺堰,
open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
var bounds = self.bounds
let widthDelta = max(17 - bounds.width, 0)
let heightDelta = max(17 - bounds.height, 0)
bounds = bounds.insetBy(dx: -widthDelta, dy: -heightDelta)
return bounds.contains(point)
}