異形按鈕的點選區域處理

Whip發表於2019-06-13

要實現如下圖的密集排列並且相互遮擋的菱形按鈕效果:

異形按鈕的點選區域處理

其UI層級的排列如下:

異形按鈕的點選區域處理

正常情況下層的按鈕一定會被上層的按鈕遮擋,那麼當點選按鈕的下半部分,其實是點選遮擋它的按鈕的透明區域。

這裡解決方案特別簡單,只需要將自定義按鈕,並將需要響應點選區域計算出來,並重寫響應鏈判斷的方法,讓按鈕只在菱形的點選範圍內去響應點選事件:

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event {
    UIBezierPath *touchPath = [UIBezierPath bezierPath];
    [touchPath moveToPoint:CGPointMake(0, self.frame.size.height * 0.273)];
    [touchPath addLineToPoint:CGPointMake(self.frame.size.width * 0.5, self.frame.size.height * 0.545)];
    [touchPath addLineToPoint:CGPointMake(self.frame.size.width, self.frame.size.height * 0.273)];
    [touchPath addLineToPoint:CGPointMake(self.frame.size.width * 0.5, 0)];
    [touchPath closePath];
    
    if ([touchPath containsPoint:point]) {
        return YES;
    } else {
        return NO;
    }
}
複製程式碼

這裡沒有通過數學函式的座標去計算,太麻煩了,我是通過貝塞爾曲線畫出來了響應的區域,然後通過判斷點選的位置在不在這個區域來實現。

相關文章