ios - UIButton自定义属性
黄舟
黄舟 2017-04-17 11:08:54
[iOS讨论组]

我要给UIButton自定义一个属性,我这样做的

MyUIButton.h

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

MyUIButton.m

@implementation MyUIButton
@synthesize idx;
@end
#import "MyUIButton.h"
    MyUIButton *btn = ((MyUIButton *)[MyUIButton buttonWithType:UIButtonTypeRoundedRect]);
    btn.idx = @"abcd";

然后报错了:

-[UIRoundedRectButton setIdx:]: unrecognized selector sent to instance 0x816b2a0

难道这样扩展属性不对么?

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(2)
怪我咯

你代码中虽继承了UIbutton重写了init,但是未重写buttonWithType:,所以在调用[MyUIButton buttonWithType:UIButtonTypeRoundedRect]时实际上调用了父类的buttonWithType:,父类的buttonWithType:调用了某种UIButtoninit

为什么我说是某种UIButton?因为UIButtonbuttonWithType:可以生成不同类型的对象,这些对象都是UIButton的子类。(当然不可能生成MyUIButton类型的对象,也就无法响应setIdx:方法)

实际上,UIButton是一种聚类,你不能直接继承它。应当增加扩展,使用运行时增加关联对象。注意.m中引入了#import <objc/runtime.h>

@interface UIButton (IdxProperty)
@property (nonatomic,retain) NSString *idx;
@end

#import <objc/runtime.h>
@implementation MyUIButton
@dynamic idx;
@end

- (NSString *)idx
{
    NSString *idx = objc_getAssociatedObject(self, @"kUIButtonIdxKey");
    return idx;
}

- (void)setIdx:(NSString *)idx
{
    objc_setAssociatedObject(self, @"kUIButtonIdxKey", idx, OBJC_ASSOCIATION_RETAIN);
}

更干净的写法是给@"kUIButtonIdxKey"加个宏。此处我写的有点dirty
楼主,还是那句话,加强下面向对象的学习

巴扎黑
-(id)buttonWithType:(UIButtonType)type
{
  [super buttonWithType:type]; 
   self.idx = @"abcd";
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号