- 今天寫demo的時(shí)候發(fā)現(xiàn)一個(gè)問題,在一個(gè)view上創(chuàng)建了一個(gè)button,這個(gè)button怎么點(diǎn)都不執(zhí)行點(diǎn)擊方法,感覺很奇怪,找來找去還是找不到原因,廣大的iOS開發(fā)小伙伴們來看看是什么問題。
首先我有一個(gè)在ViewController上創(chuàng)建了一個(gè)TestView,心血來潮了直接用了init方法,沒有用-(instancetype)initWithFrame方法創(chuàng)建。
TestView *testView = [[TestView alloc]init];
[self.view addSubview:testView];
TestView類的實(shí)現(xiàn)文件里面:
#import "TestView.h"
@implementation TestView
- (void)layoutSubviews {
[super layoutSubviews];
self.button.frame = CGRectMake(100, 100, 100, 44);
}
- (instancetype)init {
if (self = [super init]) {
self.button = [UIButton buttonWithType:UIButtonTypeCustom];
[self.button setBackgroundColor:[UIColor redColor]];
[self.button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:self.button];
}
return self;
}
- (void)buttonAction:(UIButton *)sender {
}
@end
這樣的話button是被添加上了,testView也添加上了,但是點(diǎn)擊該button的時(shí)候,點(diǎn)擊方法不執(zhí)行。是沒有設(shè)置testView的frame的問題。但是為什么沒設(shè)置frame控件還添加上了?
正常創(chuàng)建
TestView *view = [[TestView alloc]initWithFrame:self.view.bounds];
[self.view addSubview:view];
TestView實(shí)現(xiàn)文件:
#import "TestView.h"
@implementation TestView
- (void)layoutSubviews {
[super layoutSubviews];
self.button.frame = CGRectMake(100, 100, 100, 44);
}
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
self.button = [UIButton buttonWithType:UIButtonTypeCustom];
[self.button setBackgroundColor:[UIColor redColor]];
[self.button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:self.button];
}
return self;
}
- (void)buttonAction:(UIButton *)sender {
}
@end
這樣寫就沒問題了。