【问题标题】:How to give an external property to UIButton如何给 UIButton 一个外部属性
【发布时间】:2012-02-27 08:36:57
【问题描述】:

我是 iOS 开发的新手。现在我想给 UIButton 一个外部属性(类似于标签)。有可能吗?如果可以的话,该怎么做?

如果有人知道,请帮助我。

【问题讨论】:

  • 从 UIButton 创建您的自定义类。

标签: objective-c xcode4 ios4 uibutton


【解决方案1】:

可以使用NSArray,数组的索引就是UIButton的标签。

【讨论】:

    【解决方案2】:

    您可以创建UIButton 子类,也可以像这样使用 Obj-C 运行时关联

    #import <objc/runtime.h>
    
    static char kMyExtendedPropKey;
    objc_setAssociatedObject(myButton,
                             &kMyExtendedPropKey,
                             yourObjectToAssociate,
                             OBJC_ASSOCIATION_RETAIN);
    

    请注意,关联可以与类别结合使用以向现有类添加新属性!但请谨慎使用,子类化是首选方式

    【讨论】:

      【解决方案3】:

      子类 UIButton,假设你想要一个 NSString 在你的按钮:

      .h

      @interface MyAttributedButton : UIButton {
         NSString *myExternalProperty;
       }
      
      @property(nonatomic, retain) NSString *myExternalProperty;
      @end
      

      .m

      @implementation MyAttributedButton
      @synthesize myExternalProperty;
      @end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多