美文网首页iOS-Objective-C
button的点击方法不执行

button的点击方法不执行

作者: 追沐 | 来源:发表于2017-07-24 21:43 被阅读2次
  • 今天写demo的时候发现一个问题,在一个view上创建了一个button,这个button怎么点都不执行点击方法,感觉很奇怪,找来找去还是找不到原因,广大的iOS开发小伙伴们来看看是什么问题。

首先我有一个在ViewController上创建了一个TestView,心血来潮了直接用了init方法,没有用-(instancetype)initWithFrame方法创建。

TestView *testView = [[TestView alloc]init];
[self.view addSubview:testView];

TestView类的实现文件里面:

#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也添加上了,但是点击该button的时候,点击方法不执行。是没有设置testView的frame的问题。但是为什么没设置frame控件还添加上了?

正常创建

TestView *view = [[TestView alloc]initWithFrame:self.view.bounds];
[self.view addSubview:view];

TestView实现文件:

#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

这样写就没问题了。

相关文章

网友评论

    本文标题:button的点击方法不执行

    本文链接:https://www.haomeiwen.com/subject/wvlikxtx.html