【问题标题】:UIButton class fails to recognize selector after adding as a subview to a UIViewUIButton 类在作为子视图添加到 UIView 后无法识别选择器
【发布时间】:2012-09-28 17:13:36
【问题描述】:

我有一个 UIViewController 类,我试图在其中分配一个 UIButton 类。这是一个示例代码。

MyViewController.m 
- (void)viewDidLoad
{
CGRect frame = CGRectMake(companybuttonxOffset, companybuttonyOffset, buttonWidth, buttonHeight);
CustomButton *customButton = [[CustomButton alloc]initWithFrame:frame];
[self.view addSubview:customButton];
[super viewDidLoad];
}
CustomButton.h

#import <UIKit/UIKit.h>

@interface CustomButton : UIButton {
}
@property (nonatomic, assign) NSInteger toggle;
- (void)buttonPressed: (id)sender;
@end


CustomButton.m

#import "CustomButton.h"

@implementation CustomButton
@synthesize toggle;
- (id) initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
//custom button code
[self addTarget: self action: @selector(buttonPressed:) forControlEvents: UIControlEventTouchUpInside];

}
return self;
}
- (void)buttonPressed: (id)sender
{
    NSLog(@"buttonPressed !!!!!");
}
@end

虽然按钮存在于我的视图控制器中,但如果我按下按钮,我会不断收到此错误 - -[UIButton buttonPressed:]: unrecognized selector sent to instance 0xb1dca50

根据我在搜索了很多答案后的理解是,当您在 IB 中对按钮进行子类化时,initWithFrame 永远不会被调用。相反,我应该使用 initWithCoder。这是正确的吗 ?如果是这样,那么我不知道 NSCoder 是什么,以及如何使用它。
我厌倦了为此寻找解决方案,请帮助我。

【问题讨论】:

  • 你在IB做点什么吗?您正在代码中创建此按钮,因此应该调用 initWithFrame: -- 只需在其中输入一个日志进行测试。我认为更大的问题是 buttonPressed: 方法应该在您的视图控制器中而不是在按钮代码中——这是标准的 MVC 设计。
  • @Farhan 你能解决这个问题吗?关于我的答案,我可以解释更多吗?

标签: ios uibutton gui-builder


【解决方案1】:

我猜在 IB 中,您没有将按钮的类更改为 CustomButton。 因此,它仍然是一个 UIButton。

不过,我在这里支持 rdelmar,认为这不是一个很好的设计。 你的视图控制器应该处理事件,而不是按钮本身。

【讨论】:

    【解决方案2】:

    虽然我同意您通常应该将所有目标都放在控制器层中,但请尝试一下:

    - (id)initWithCoder:(NSCoder *)coder
    {
        if (self = [super initWithCoder:coder])
        {
            [self customButtonInit];
        }
    
        return self;
    }
    
    
    - (id)initWithFrame:(CGRect)frame
    {
        if (self = [super initWithFrame:frame])
        {
            [self customButtonInit];
        }
    
        return self;
    }
    
    
    - (void)customButtonInit
    {
        [self addTarget: self action: @selector(buttonPressed:) forControlEvents: UIControlEventTouchUpInside];
    }
    

    【讨论】:

    • 非常感谢,虽然我有疑问,如果我要在代码中使用 init,如何初始化视图控制器内的按钮类,是否与 - CustomButton *customButton = [[ CustomButton alloc]initWithFrame:frame];或者还有什么别的吗?
    • @Farhan.iOSDeveloper 你不会想直接打电话给initWithCoder:——当你把你的按钮从笔尖里拿出来时就会调用它。也就是说,如果您在 nib / storyboard 中创建一个按钮,并将其类设置为您的 CustomButton,那么将调用 initWithCoder:。因此,您只需要担心在从 nib 或情节提要加载视图时调用它。您只需要实现该方法,如图所示。然后在界面生成器中分配类。这能回答你的问题吗?
    猜你喜欢
    • 2014-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多