閑談UIButton分類(工具)

開頭

在開始還是來扯點(diǎn)其他的.下午睡覺睡到五六點(diǎn)鐘,然后去附近的學(xué)校小跑了會(huì).由于學(xué)校距離公司很近,順便就到公司搗鼓搗鼓代碼.反正閑著也是閑著.

今天的重點(diǎn)

今天重點(diǎn)在于通過runtime來為button添加一些類似快捷設(shè)置的功能.其實(shí)就是為類添加新的屬性.技術(shù)含量確實(shí)不是很高.網(wǎng)上都把這個(gè)寫泛濫了.里面有一些注釋不同于其他的在于我是用英文注釋的(在這里裝個(gè)逼,O(∩_∩)O~)

具體功能點(diǎn)

  • 設(shè)置button在一定時(shí)間間隔內(nèi)不能再次點(diǎn)擊.
    這個(gè)功能其實(shí)在項(xiàng)目中也是比較常見的.舉個(gè)例子,當(dāng)你的項(xiàng)目運(yùn)行不是很流暢的時(shí)候(通常出現(xiàn)在比較大的項(xiàng)目中),連續(xù)點(diǎn)擊會(huì)觸發(fā)多次事件,造成比如多次請(qǐng)求網(wǎng)絡(luò),多次push等.

  • button快速設(shè)置不同狀態(tài)下的背景顏色(button設(shè)置背景顏色不是根據(jù)狀態(tài)的哦)

  • 快速添加block代替addTarget,其實(shí)就是著名的(blockkit)里面早就做了.

先來看看效果吧

TestImage.gif

中間其實(shí)是一個(gè)button,這里設(shè)置的是3秒之后才能觸發(fā)點(diǎn)擊事件.

 UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:btn];
    btn.frame = CGRectMake(0, 0, 40, 40);
    [btn centerToParentNoScale];
    
    btn.backgroundColor = [UIColor greenColor];
    [btn setBackgroundColor:[UIColor greenColor] forState:UIControlStateNormal];
    [btn setBackgroundColor:[UIColor redColor] forState:UIControlStateHighlighted];
    
    btn.timeInterval = 3.0;
    [btn addActionHandler:^(NSInteger tag) {
        self.view.backgroundColor = RandomColor;
    }]; 

詳細(xì)代碼(為了做成工具,功能點(diǎn)寫在一個(gè)分類里面)

.h文件

#import <UIKit/UIKit.h>

typedef void (^TouchedBlock)(NSInteger tag);

@interface UIButton (XLKit)

/**
 *  Click on the button how much time interval is not responding
 */
@property (nonatomic, assign) NSTimeInterval timeInterval;

/**
 *  With the background color of different color Settings button state (the default background color is not change with state)
 */
- (void)setBackgroundColor:(UIColor *)backgroundColor
                  forState:(UIControlState)state;
/**
 *  Add block repalce addtarget
 */
- (void)addActionHandler:(TouchedBlock)touchHandler;
@end

.m文件

@interface UIButton ()

/**
 *  Is to ignore the button Touch Event
 */
@property (nonatomic, assign) BOOL isIgnoreTouch;

@end

@implementation UIButton (XLKit)

#pragma mark -
#pragma mark - TouchInterval
- (NSTimeInterval)timeInterval {
    return [objc_getAssociatedObject(self, _cmd) doubleValue];
}

- (void)setTimeInterval:(NSTimeInterval) timeInterval {
    objc_setAssociatedObject(self, @selector(timeInterval), @(timeInterval), OBJC_ASSOCIATION_ASSIGN);
}

- (BOOL)isIgnoreTouch {
    // _cmd == @selector(isIgnoreTouch)
    return [objc_getAssociatedObject(self, _cmd) boolValue];
}

- (void)setIsIgnoreTouch:(BOOL)isIgnoreTouch {
    objc_setAssociatedObject(self, @selector(isIgnoreTouch), @(isIgnoreTouch), OBJC_ASSOCIATION_ASSIGN);
}

#pragma mark - Load & Swilling
+ (void)load {
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        SEL orginSEL = @selector(sendAction:to:forEvent:);
        SEL newSEL = @selector(newSendAction:to:forEvent:);
        
        Method orginMethod = class_getInstanceMethod(self, orginSEL);
        Method newMethod = class_getInstanceMethod(self, newSEL);
        
        // The realization of the newMethod is added to the system method That is to say, Add orginMethod method Pointers into method newMethod return value indicates whether or not to add a success
        BOOL isAdd = class_addMethod(self, orginSEL, method_getImplementation(newMethod), method_getTypeEncoding(newMethod));
        
        // Add a success So at this moment does not exist in this class that newMethod methods must be newMethod orginMethod pointer into method, otherwise the newMethod method will not be implemented.
        if (isAdd) {
            class_replaceMethod(self, newSEL, method_getImplementation(orginMethod), method_getTypeEncoding(orginMethod));
        }else{
            // If add failed With the realization of the newMethod in this class, now just need to orginMethod and newMethod IMP exchange.
            method_exchangeImplementations(orginMethod, newMethod);
        }
    });
}

// When click on the button event sendAction will perform newSendAction
- (void)newSendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
    
    if ([self isKindOfClass:[UIButton class]]) {
        if (!self.isIgnoreTouch) {
            self.timeInterval = self.timeInterval == 0 ? 0:self.timeInterval;
        };
        
        if (self.isIgnoreTouch) {
            return;
        }
        
        if (self.timeInterval > 0) {
            self.isIgnoreTouch = YES;
            
            // Note this is perform on the current thread using the default mode after a delay.
            [self performSelector:@selector(setIsIgnoreTouch:)
                       withObject:nil
                       afterDelay:self.timeInterval];
        }
        
    }
    [self newSendAction:action to:target forEvent:event];
}

#pragma mark -
#pragma mark - BackgroudColor
- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state {
    [self setBackgroundImage:[UIButton imageWithColor:backgroundColor] forState:state];
}

+ (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

#pragma mark -
#pragma mark - Block repalce AddTarget
-(void)addActionHandler:(TouchedBlock)touchHandler {
    objc_setAssociatedObject(self, @selector(actionTouched:), touchHandler, OBJC_ASSOCIATION_COPY_NONATOMIC);
    [self addTarget:self action:@selector(actionTouched:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)actionTouched:(UIButton *)btn {
    TouchedBlock block = objc_getAssociatedObject(self, _cmd);
    if (block) {
        block(btn.tag);
    }
}
@end

后記

該回去了,代碼就差不多如上所示.注釋使用英文寫的(只為裝逼,大神似乎都是這樣哦!).
建議看看Swilling(方法交換)的具體實(shí)現(xiàn).如Method,IMP,SEL.三者之間的關(guān)系.因?yàn)槲颐嬖囘^好多人,幾乎都不知道.O(∩_∩)O~.
玩得愉快

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市霍比,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌们豌,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,907評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件望迎,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡涛浙,警方通過查閱死者的電腦和手機(jī)摄欲,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,987評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來我注,“玉大人迟隅,你說我怎么就攤上這事≈窍” “怎么了?”我有些...
    開封第一講書人閱讀 164,298評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵校哎,是天一觀的道長(zhǎng)瞳步。 經(jīng)常有香客問我,道長(zhǎng)谚攒,這世上最難降的妖魔是什么氛堕? 我笑而不...
    開封第一講書人閱讀 58,586評(píng)論 1 293
  • 正文 為了忘掉前任讼稚,我火速辦了婚禮括儒,結(jié)果婚禮上锐想,老公的妹妹穿的比我還像新娘。我一直安慰自己固逗,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,633評(píng)論 6 392
  • 文/花漫 我一把揭開白布烫罩。 她就那樣靜靜地躺著,像睡著了一般盗誊。 火紅的嫁衣襯著肌膚如雪隘弊。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,488評(píng)論 1 302
  • 那天开镣,我揣著相機(jī)與錄音串结,去河邊找鬼哑子。 笑死肌割,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的弥奸。 我是一名探鬼主播,決...
    沈念sama閱讀 40,275評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼盛霎,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼耽装!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起规个,我...
    開封第一講書人閱讀 39,176評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤姓建,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后速兔,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,619評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡谍婉,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,819評(píng)論 3 336
  • 正文 我和宋清朗相戀三年屡萤,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了珍剑。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,932評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡招拙,死狀恐怖措译,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情领虹,我是刑警寧澤,帶...
    沈念sama閱讀 35,655評(píng)論 5 346
  • 正文 年R本政府宣布诉稍,位于F島的核電站最疆,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏努酸。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,265評(píng)論 3 329
  • 文/蒙蒙 一仍源、第九天 我趴在偏房一處隱蔽的房頂上張望舔涎。 院中可真熱鬧,春花似錦亡嫌、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,871評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至女蜈,卻和暖如春色瘩,著一層夾襖步出監(jiān)牢的瞬間逸寓,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,994評(píng)論 1 269
  • 我被黑心中介騙來泰國(guó)打工泥栖, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留勋篓,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,095評(píng)論 3 370
  • 正文 我出身青樓钢颂,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親殊鞭。 傳聞我的和親對(duì)象是個(gè)殘疾皇子尼桶,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,884評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,129評(píng)論 25 707
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理疯汁,服務(wù)發(fā)現(xiàn),斷路器幌蚊,智...
    卡卡羅2017閱讀 134,656評(píng)論 18 139
  • ¥開啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個(gè)線程,因...
    小菜c閱讀 6,419評(píng)論 0 17
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫蜒简、插件漩仙、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,103評(píng)論 4 62
  • 青山溪雲(yún)閱讀 149評(píng)論 0 0