在isKindOfClass中未检测到从UIButton继承的自定义类:

时间:2013-01-28 05:02:22

标签: ios iphone objective-c uibutton

我创建了一个自定义按钮类,其中包含一些继承自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类]的条件下。请帮助我解决我做错了什么或者需要做些什么。

1 个答案:

答案 0 :(得分:5)

这是因为buttonWithTypeUIButton的类方法,它返回UIButton类型,虽然您的EFButton继承了UIButton,但它无法返回EFButton类型

引用开发人员documents

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

PS:我不认为继承UIButton是一种好方法。