button的點(diǎn)擊方法不執(zhí)行

  • 今天寫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

這樣寫就沒問題了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 文‖颯愷 看晨讀時(shí)候,腦子里揮之不去的是小時(shí)候家里的情形。 從我記事起,家里遇到什么事總是喜歡自己解決。如果這件工...
    百日跑者孫大剩閱讀 541評(píng)論 8 6
  • 霧失樓臺(tái),月迷津渡,桃源望斷無尋處??煽肮吗^閉春寒,杜鵑聲里斜陽暮。驛寄梅花,魚傳尺素,切成此恨無重塑。郴(che...
    Www劉閱讀 476評(píng)論 1 0
  • 冥想,是瑜伽中的一項(xiàng)技法,它通過獲得深度的寧靜狀態(tài)而增強(qiáng)自我知識(shí)和良好狀態(tài)。在最初接觸瑜伽的時(shí)候,老想著趕緊練...
    風(fēng)煙俱盡閱讀 383評(píng)論 5 5
  • 大半夜失眠 一年前的這天,似乎也是如此失眠,完全徹底的脫離了高考,告別了青春和無知。 我的高三似乎也沒有多么轟轟烈...
    松ER閱讀 410評(píng)論 0 0
  • 當(dāng)一個(gè)人被大家稱贊其聰明時(shí),你能想起些什么?或許你的腦海中將浮現(xiàn)出一個(gè)受過良好教育而且智力超群的人的形象。但是實(shí)際...
    Jodoo閱讀 3,773評(píng)論 9 107

友情鏈接更多精彩內(nèi)容