【问题标题】:custom class inheriting from UIButton not detected in isKindOfClass:在 isKindOfClass 中未检测到从 UIButton 继承的自定义类:
【发布时间】:2016-02-01 22:17:44
【问题描述】:

我创建了一个自定义按钮类,其中包含一些继承自 UIButton 的额外属性。它通过普通按钮添加到如下视图中:

EFButton *btn = [EFButton buttonWithType:UIButtonTypeRoundedRect];    
btn.frame = CGRectMake(500, 100, 100, 44);
btn.backgroundColor = [UIColor lightGrayColor];
btn.userInteractionEnabled = NO;
[self.view addSubview:btn];

UIButton *nBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];    
nBtn.frame = CGRectMake(500, 100, 100, 44);
nBtn.backgroundColor = [UIColor lightGrayColor];
nBtn.userInteractionEnabled = NO;
[self.view addSubview:nBtn];

遍历视图中的对象,例如:

  for (id view in self.view.subviews) 
{

    if ([view isKindOfClass:[EFButton class]]) 
    {
        //** dsnt come here **
        NSLog(@"EFButton Class");
        EFButton *btn = view;
    }
    if ([view isKindOfClass:[UIButton class]]) 
    {
        //** come here **
        NSLog(@"UIButton Class");
        UIButton *btn = view;
    }
}

UIButton 是有效的,但它不在 isKindOfClass:[EFButton class] 的条件下。请帮助我解决我做错了什么或需要如何做。

【问题讨论】:

    标签: ios iphone objective-c uibutton


    【解决方案1】:

    因为buttonWithTypeUIButton的类方法,它返回UIButton类型,虽然你的EFButton继承了UIButton,但不能返回EFButton类型

    引用开发者documents

    If you subclass UIButton, this method does not return an instance of your subclass
    

    PS:我不认为继承UIButton是个好办法。

    【讨论】:

    • 是的,如果您没有在EFButton 中编写buttonWithType: 的实现,这就是正在发生的事情。另外,UIButtonTypeCustom 是为了避免子类化...
    • 为了在 UIButton 类中添加一些额外的属性可以做些什么。
    • @HassanWaheed 你可以为 UIButton 添加一个 Category ,为 UIButton 添加额外的“属性”。伪造实例变量。(怎么做你可以看看这个:oleb.net/blog/2011/05/…
    • 你可以使用 alloc 和 init 创建一个按钮。尽管它看起来很奇怪。但它来自开发人员文档。我尝试了 init 方法,它可以工作。所以你不需要添加类别。只需子类就可以了。
    猜你喜欢
    • 2015-06-20
    • 1970-01-01
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多