iOS 利用運行時交換系統方法實現禁止同時點擊兩個按鈕觸發多個事件

來源:互聯網
上載者:User

標籤:

#import "UIViewController+Parents.h"

/** 匯入標頭檔 */

#import <objc/runtime.h>

 

@implementation UIViewController (Parents)

 

//load方法會在類第一次載入的時候被調用

//調用的時間比較靠前,適合在這個方法裡做方法交換

+ (void)load{

    //方法交換應該被保證,在程式中只會執行一次

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        //獲得viewController的生命週期方法的selector

        SEL systemSel = @selector(viewDidDisappear:);

        //自己實現的將要被交換的方法的selector

        SEL swizzSel = @selector(swiz_viewDidDisappear:);

        //兩個方法的Method

        Method systemMethod = class_getInstanceMethod([self class], systemSel);

        Method swizzMethod = class_getInstanceMethod([self class], swizzSel);

        //首先動態添加方法,實現是被交換的方法,傳回值表示添加成功還是失敗

        BOOL isAdd = class_addMethod(self, systemSel, method_getImplementation(swizzMethod), method_getTypeEncoding(swizzMethod));

        if (isAdd) {

            //如果成功,說明類中不存在這個方法的實現

            //將被交換方法的實現替換到這個並不存在的實現

            class_replaceMethod(self, swizzSel, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));

        }else{

            //否則,交換兩個方法的實現

            method_exchangeImplementations(systemMethod, swizzMethod);

        }

    });

}

- (void)swiz_viewDidDisappear:(BOOL)animated{

    //這時候調用自己,看起來像是死迴圈

    //但是其實自己的實現已經被替換了

    [self swiz_viewDidDisappear:animated];

    [self setExclusiveTouchForButtons:self.view];

    NSLog(@"swizzle");

}

-(void)setExclusiveTouchForButtons:(UIView *)myView

{

    for (UIView * v in [myView subviews]) {

        if([v isKindOfClass:[UIButton class]])

            [((UIButton *)v) setExclusiveTouch:YES];

        else if ([v isKindOfClass:[UIView class]]){

            [self setExclusiveTouchForButtons:v];

        }

    }

}

 

iOS 利用運行時交換系統方法實現禁止同時點擊兩個按鈕觸發多個事件

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.