繼承UIView自定義button的addTarget


前幾天去面試,面試官問(wèn)到繼承UIView實(shí)現(xiàn)和系統(tǒng)UIButton相似的監(jiān)聽(tīng)方法,心里面知道這是難為人的問(wèn)題,其實(shí)沒(méi)啥用,但是還是打算寫(xiě)出來(lái),分享給需要的小伙伴.

一.自定義Button首先了解一下UIView的觸摸事件:

/** 1.當(dāng)觸摸開(kāi)始時(shí)會(huì)調(diào)用下面的事件 */

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event;

/** 2.當(dāng)觸摸移動(dòng)時(shí)會(huì)調(diào)用下面的事件 */

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent*)event;

/** 3.當(dāng)觸摸結(jié)束時(shí)會(huì)調(diào)用下面的事件 */

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent*)event;

/** 4.當(dāng)觸摸取消時(shí)會(huì)調(diào)用下面的事件 */

-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent*)event;

所以,在封裝自己的button時(shí),會(huì)用到上述的方法觸發(fā)回調(diào);

二.實(shí)現(xiàn)

首先新建一個(gè)TTButton類(lèi),繼承于UIView, 在TTButton類(lèi)中自定義button.下面要為自定義Button添加target和action接口,步驟如下:

1.在TTButton.h中聲明方法:

//添加targetAction回調(diào)

-(void)addTarget:target action:(SEL)action;

2.在TTButton.m中進(jìn)行實(shí)現(xiàn):

(1),添加私有擴(kuò)展屬性:

@interface TTButton()

/** target */

@property(nonatomic, weak) id target;

/** action */

@property(nonatomic, assign) SEL action;

@end

(2),方法實(shí)現(xiàn):

//回調(diào)

-(void)addTarget:(id)target action:(SEL)action

{

? ? ? ? self.target= target;

? ? ? ? self.action= action;

}

-(void)touchesEnded:(NSSet *) touches withEvent:(UIEvent*) event

{

? ? ? ? //獲取觸摸對(duì)象

? ? ? ? UITouch *touche = [touches anyObject];

? ? ? ?//獲取touche的位置

? ? ? CGPoint point = [touche locationInView: self];

? ? ? ?//判斷點(diǎn)是否在button中

? ? ? ?if(CGRectContainsPoint(self.bounds, point)) {

? ? ? ? //執(zhí)行action

? ? ? ? [self.target ?performSelector: self.action withObject: self];

? ? ? ? ?}

}

3.如何使用:

導(dǎo)入頭文件使用一下:

TTButton *btn = [[TTButton alloc] initWithFrame:CGRectMake(100,100,100,30)];

btn.backgroundColor = [UIColor redColor];

[btn addTarget: self action:@selector(btnClick)];

[self.view addSubview: btn];


-(void)btnClick

{

? ? ? ?TTLog(@"黃文濤");

}


到此就結(jié)束了,歡迎交流指正, 本人QQ:1334627194

最后編輯于
?著作權(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)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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