
解决示例
1、定义子视图
// .h文件
#import <UIKit/UIKit.h>
@interface ButtonView : UIView
@property (nonatomic, copy) void (^buttonClick)(UIButton *button);
@end
// .m文件
#import "ButtonView.h"
@interface ButtonView ()
@property (nonatomic, strong) UIButton *subButton;
@end
@implementation ButtonView
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setUI];
}
return self;
}
- (void)setUI
{
//
UIButton *button = [[UIButton alloc] initWithFrame:self.bounds];
[self addSubview:button];
button.backgroundColor = [UIColor greenColor];
[button addTarget:self action:@selector(btn1Click:) forControlEvents:UIControlEventTouchUpInside];
button.tag = 1;
//
self.subButton = [[UIButton alloc] initWithFrame:CGRectMake(100, -40, 80, 80)];
[self addSubview:self.subButton];
self.subButton.backgroundColor = [UIColor redColor];
[self.subButton setTitle:@"click" forState:UIControlStateNormal];
[self.subButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.subButton setTitleColor:[UIColor yellowColor] forState:UIControlStateHighlighted];
[self.subButton addTarget:self action:@selector(btn2Click:) forControlEvents:UIControlEventTouchUpInside];
self.subButton.layer.cornerRadius = 40;
self.subButton.layer.masksToBounds = YES;
self.subButton.tag = 2;
}
- (void)btn1Click:(UIButton *)button
{
if (self.buttonClick) {
self.buttonClick(button);
}
}
- (void)btn2Click:(UIButton *)button
{
if (self.buttonClick) {
self.buttonClick(button);
}
}
// 在view中重写以下方法,其中self.button就是那个希望被触发点击事件的按钮
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
UIView *view = [super hitTest:point withEvent:event];
if (view == nil) {
// 转换坐标系
CGPoint newPoint = [self.subButton convertPoint:point fromView:self];
// 判断触摸点是否在button上
if (CGRectContainsPoint(self.subButton.bounds, newPoint)) {
view = self.subButton;
}
}
return view;
}
@end
2、使用
ButtonView *buttonView = [[ButtonView alloc] initWithFrame:CGRectMake(20, 120, (self.view.frame.size.width - 40), 200)];
[self.view addSubview:buttonView];
buttonView.buttonClick = ^(UIButton *button) {
NSString *message = [NSString stringWithFormat:@"点击了按钮 %ld", button.tag];
[[[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"知道了", nil] show];
};
效果图

注意,主要是实现该方法
// 在view中重写以下方法,其中self.button就是那个希望被触发点击事件的按钮
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
UIView *view = [super hitTest:point withEvent:event];
if (view == nil) {
// 转换坐标系
CGPoint newPoint = [self.subButton convertPoint:point fromView:self];
// 判断触摸点是否在button上
if (CGRectContainsPoint(self.subButton.bounds, newPoint)) {
view = self.subButton;
}
}
return view;
}
网友评论