zoukankan      html  css  js  c++  java
  • Runtime 实现 动态添加属性

    利用动态加载为对象添加一个 block 点击属性;

    .h 文件

    1 #import <UIKit/UIKit.h>
    2 
    3 @interface UIView (Tap)
    4 /**
    5  *  动态添加手势 
    6  */
    7 - (void)setTapActionWithBlock:(void (^)(void))block ;
    8 @end

    .m 文件

     1 #import "UIView+Tap.h"
     2 #import <objc/runtime.h>
     3 /**
     4  *  动态添加手势
     5  */
     6 static const char *ActionHandlerTapGestureKey;
     7 
     8 @implementation UIView (Tap)
     9 
    10 - (void)setTapActionWithBlock:(void (^)(void))block {
    11     
    12     self.userInteractionEnabled = YES;
    13     
    14     UITapGestureRecognizer *gesture = objc_getAssociatedObject(self, &ActionHandlerTapGestureKey);
    15     
    16     if (!gesture) {
    17         gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleActionForTapGesture:)];
    18         [self addGestureRecognizer:gesture];
    19         objc_setAssociatedObject(self, &ActionHandlerTapGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
    20     }
    21     
    22     objc_setAssociatedObject(self, &ActionHandlerTapGestureKey, block, OBJC_ASSOCIATION_COPY);
    23 }
    24 
    25 - (void)handleActionForTapGesture:(UITapGestureRecognizer *)gesture {
    26     if (gesture.state == UIGestureRecognizerStateRecognized)  {
    27         void(^action)(void) = objc_getAssociatedObject(self, &ActionHandlerTapGestureKey);
    28         if (action)  {
    29             action();
    30         }
    31     }
    32 }
    33 @end
  • 相关阅读:
    STL源码剖析之_allocate函数
    PAT 1018. Public Bike Management
    PAT 1016. Phone Bills
    PAT 1012. The Best Rank
    PAT 1014. Waiting in Line
    PAT 1026. Table Tennis
    PAT 1017. Queueing at Bank
    STL源码剖析之list的sort函数实现
    吃到鸡蛋好吃,看看是哪只母鸡下的蛋:好用的Sqlite3
    cJSON
  • 原文地址:https://www.cnblogs.com/guangleijia/p/6066628.html
Copyright © 2011-2022 走看看