单击时显示(null)的按钮,即使在禁用时也是如此

时间:2014-04-20 18:01:42

标签: ios objective-c

我的故事板上有一些按钮,我删除了所有文本,然后我以编程方式添加文本,因此当应用程序启动时,按钮是不可见的。但是,如果用户点击了任何一个按钮,那么按钮的所有四个都会在按钮的标签部分显示(null)。我认为这可能是因为按钮已启用,因此我在UIView子类的initWithFrame方法中添加了此代码,其中按钮是属性,但它没有更改任何内容。

此外,我不明白为什么单击其中一个按钮会在所有四个按钮的标签区域中显示(null)。

 - (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    if (self) {
        // Initialization code
        self.button1.enabled= NO;
        self.button2.enabled= NO;
        self.button3.enabled= NO;
        self.button4.enabled= NO;


    }
    return self;
}

然后我考虑过,当我认为这种方法时,这个initWithFrame方法可能无法运行。我尝试了UIView的子视图,并没有改变结果

-(id)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {

        self.answerChoice1.enabled= NO;
        self.answerChoice2.enabled= NO;
        self.answerChoice3.enabled= NO;
        self.answerChoice4.enabled= NO;
    }
    return self;
}

如果点击其中任何一个按钮,你能解释为什么所有四个按钮都显示(null)吗?

1 个答案:

答案 0 :(得分:0)

这取决于我想在按钮调用的选择器上,以及你是否能够区分按钮。

您可以使用button.tag属性区分按钮,如下所示:

    // declare and allocate
    UIButton* button1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    // set frame
    button1.frame = frameButton1;
    // add to view
    [self.view addSubview: button1];

    // properties from docs
    // button1.enabled or button1.hidden or button1 setTitle.. here

    // add selector
    [button1 addTarget:self selector:@selector(buttonAction:) ..UIEventTouchUpInside];

    // add identifier, integer in this case
    button1.tag = 1;

    // repeat for other buttons


    // in your selector
    - (void)buttonAction:(UIButton *)sender
    {
        // identify button
        switch (sender.tag) {
            case 0:
                // perform action
                [self doAction];
                break;

                //..
        }

        // perform shared actions

    }
相关问题