簡介
UIView
提供了一個pointInside:withEvent:
方法,用于判斷用戶點擊的點是否屬于當前這個視圖,其定義如下:
@interface UIView
// default returns YES if point is in bounds
- (BOOL)pointInside:(CGPoint)point withEvent:(nullable UIEvent *)event;
@end
用法示例
比如說美工給我們提供了一張圓形的底色透明的png圖片,如下所示:
?圓形透明圖片.png
現在要求點擊圖片上圓形部分可以觸發(fā)單擊事件,點擊圖片的其它區(qū)域不做任何反應,這里有2種方案可以實現:
方案1
把圖片做成UIButton,并設置UIButton的layer.cornerRadius
為圓形的半徑:
UIImage *image = [UIImage imageNamed:@"圓形透明圖片.png"];
UIButton *btnView = [UIButton buttonWithType:UIButtonTypeCustom];
[btnView setImage:image forState:UIControlStateNormal];
btnView.frame = CGRectMake(0, 0, image.size.width, image.size.height);
// 設置UIButton為圓形,并且半徑與圖片半徑一致
btnView.layer.cornerRadius = image.size.width / 2.0;
btnView.clipsToBounds = YES;
[btnView addTarget:self action:@selector(buttonTapped)
forControlEvents:UIControlEventTouchUpInside];
方案2
用pointInside:withEvent:
來實現
先為UIButton定義一個擴展UIButton (Circle)
,用于設置圓形圖片半徑,并重寫pointInside:withEvent:
方法
#import <UIKit/UIKit.h>
@interface UIButton (Circle)
// 設置圖片的圓角半徑
- (void)setCornerRadius:(CGFloat)cornerRadius;
@end
#import "UIButton+Circle.h"
#import "objc/runtime.h"
static char cornerRadiusKey;
@implementation UIButton (Circle)
- (void)setCornerRadius:(CGFloat)cornerRadius
{
objc_setAssociatedObject(self, &cornerRadiusKey, [NSString stringWithFormat:@"%f", cornerRadius], OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (CGFloat)getCornerRadius
{
NSString *str = objc_getAssociatedObject(self, &cornerRadiusKey);
return (str && str.length) ? [str floatValue] : 0;
}
/**
* 計算point點與center點的距離,
* 如果 <= cornerRadius,則表示點擊了圖片的內容區(qū)域,視為有有效點擊
* 如果 > cornerRadius, 則表示點擊了圖片的空白區(qū)域,視為無效點擊
*/
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
CGPoint center = CGPointMake(self.bounds.size.width / 2.0, self.bounds.size.height / 2.0);
CGFloat distance = sqrt(pow(point.x - center.x, 2) + pow(point.y - center.y, 2));
return distance <= [self getCornerRadius];
}
@end
下面是使用方式,:
@implementation ViewController
- (void)viewDidLoad
{
UIImage *image = [UIImage imageNamed:@"圓形透明圖片.png"];
UIButton *btnView = [UIButton buttonWithType:UIButtonTypeCustom];
[btnView setImage:image forState:UIControlStateNormal];
btnView.frame = CGRectMake(100, 100, image.size.width, image.size.height);
// 設置半徑
[btnView setCornerRadius:image.size.width / 2.0];
[btnView addTarget:self action:@selector(buttonTapped)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btnView];
}
- (void)buttonTapped
{
NSLog(@"button tapped");
}
@end
運行后可以看到:
- 當點擊了圖片內容區(qū)域,則會觸發(fā)
buttonTapped
方法 - 當點擊了圖片的空白區(qū)域,沒有任何反應。
總結
方案1 | ?方案2 | |
---|---|---|
優(yōu)點 | 代碼簡單,適用廣 | 處理比較靈活 |
缺點 | 有些特殊情況處理不了 | 稍顯復雜,適用于一些特殊情況 |