子类UIButton添加属性

Mat*_*oal 34 iphone objective-c uibutton ios

我想子类UIButton添加一些我需要的属性(不是方法...只有属性).

这是我的子类的代码:

//.h-----------------------
@interface MyButton : UIButton{
    MyPropertyType *property;
}

@property (nonatomic,retain) MyPropertyType *property;
@end

//.m--------------------------
@implementation MyButton
@synthesize property;

@end
Run Code Online (Sandbox Code Playgroud)

在这里我如何使用该类:

MyButton *btn = ((MytButton *)[MyButton buttonWithType:UIButtonTypeRoundedRect]);
btn.property = SomeDataForTheProperty;
Run Code Online (Sandbox Code Playgroud)

从哪里获得此错误:

 -[UIRoundedRectButton setProperty:]: unrecognized selector sent to instance 0x593e920
Run Code Online (Sandbox Code Playgroud)

因此,从ButtonWithType我获得一个UIRoundedRectButton,(Mybutton *)不能施展它...我需要做什么来获得一个MyButton对象?是-init唯一的解决方案?

谢谢!

Joe*_*Joe 87

请尝试使用具有关联引用的类别.它更清洁,适用于所有实例UIButton.

的UIButton + Property.h

#import <Foundation/Foundation.h>

@interface UIButton(Property)

@property (nonatomic, retain) NSObject *property;

@end
Run Code Online (Sandbox Code Playgroud)

的UIButton + Property.m

#import "UIButton+Property.h"
#import <objc/runtime.h>

@implementation UIButton(Property)

static char UIB_PROPERTY_KEY;

@dynamic property;

-(void)setProperty:(NSObject *)property
{
    objc_setAssociatedObject(self, &UIB_PROPERTY_KEY, property, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(NSObject*)property
{
    return (NSObject*)objc_getAssociatedObject(self, &UIB_PROPERTY_KEY);
}

@end
Run Code Online (Sandbox Code Playgroud)

//示例用法

#import "UIButton+Property.h"

...

UIButton *button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button1.property = @"HELLO";
NSLog(@"Property %@", button1.property);
button1.property = nil;
NSLog(@"Property %@", button1.property);
Run Code Online (Sandbox Code Playgroud)

  • 我真的不认为这是一个干净的解决方案...这是一个hacky解决方案. (2认同)
  • 在UIButton的情况下,我认为这是一个比子类更好的解决方案,因为在子类上调用buttonWithType:将不会返回具有继承方法的对象. (2认同)

Wex*_*Wex 12

你需要这样做:

MyButton *btn = [[MyButton alloc] init];
Run Code Online (Sandbox Code Playgroud)

创建按钮.该buttonWithType:UIButtonTypeRoundedRect只创建的UIButton对象.

===编辑===

如果你想使用RoundedRect按钮; 那我建议如下.基本上,我们只使用我们想要的任何属性创建一个UIView,并将所需的按钮添加到该视图.


.H

@interface MyButton : UIView
{
    int property;
}

@property int property;
@end
Run Code Online (Sandbox Code Playgroud)

.M

@implementation MyButton
@synthesize property;

- (id)initWithFrame:(CGRect)_frame
{
    self = [super initWithFrame:_frame];
    if (self)
    {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        btn.frame = self.bounds;
        [self addSubview:btn];
    }
    return self;
}

@end
Run Code Online (Sandbox Code Playgroud)

用法:

MyButton *btn = [[MyButton alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
btn.property = 42;

[self.view addSubview:btn];
Run Code Online (Sandbox Code Playgroud)

  • 现在他无法访问任何按钮方法,除非他通过属性​​暴露btn. (3认同)