Skip to content

Instantly share code, notes, and snippets.

@lawrencetg
Last active December 16, 2015 01:28
Show Gist options
  • Save lawrencetg/5354970 to your computer and use it in GitHub Desktop.
Save lawrencetg/5354970 to your computer and use it in GitHub Desktop.
介绍Method Swizzling / 延时执行Block /

Method Swizzling

#if TARGET_OS_IPHONE
#import <objc/runtime.h>
#import <objc/message.h>
#else
#import <objc/objc-class.h>
#endif

void (*gOrigLayoutSubviews)(id,SEL);
//实现layoutSubviews方法,重新摆放textField位置
static void layoutSubviewsOverride(QEntryTableViewCell* self,SEL _cmd)
{
    gOrigLayoutSubviews(self,_cmd);
    if (self.textField.tag == kTextFieldTag) {
        self.textField.frame = CGRectMake(93.0, 5.0, 159, 34.0);
    }
}

@implementation QEntryTableViewCell (MyOverride)

// 替换旧的实现, 并保存旧的实现到 gOrigLayoutSubviews
+ (void) replaceLayoutSubviewsFunction
{
    static BOOL firstTime = YES;
    if (firstTime) {
        Method origMethod =class_getInstanceMethod(self, @selector(layoutSubviews));
        gOrigLayoutSubviews = (void *)class_replaceMethod(self,@selector(layoutSubviews), (IMP)layoutSubviewsOverride,method_getTypeEncoding(origMethod));
        firstTime = NO;
    }
}

@end

延时执行Block

void RunBlockAfterDelay(NSTimeInterval delay, void (^block)(void))
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC*delay),
      dispatch_get_current_queue(), block);
}

详情参考这篇:唐巧的技术博客-使用GCD

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment