前幾天去面試,面試官問(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