“setTitle”方法不起作用

时间:2012-05-31 10:52:09

标签: iphone uibutton

每一个人。 我正在开发iphone app。

我尝试在代码中更改Button的标题。 当我单击一个按钮时,标题将更改另一个文本。

所以,我使用setTitle方法,但应用程序被杀了。

代码如下。

-(IBAction)deleteProject:(id)sender{

    UIButton *button = (UIButton *) sender;
    if (addButton.enabled == YES ){

        addButton.enabled = NO ;

        //Here, the code is stopped.
        [button setTitle:@"Back" forstate:UIControlStateNormal];
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        [mainTableView setEditing:YES animated:YES];
    }

    else{

        addButton.enabled = YES;

        //Here, the code is stopped. V
        [button setTitle:@"Delete" forstate:UIControlStateNormal];
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        [mainTableView setEditing:NO animated:YES];
    }
}

请帮帮我。

3 个答案:

答案 0 :(得分:3)

您将sender参数传递到deleteProject:方法中。此参数的类型为id,可以是任何类型。

您将其投放到UIButton并尝试将其用作UIButton

您获得的例外是[UIBarButtonItem setTitle:forState:]

这应该告诉您sender根本不是UIButton,而是UIBarButtonItem:)

您可以对此进行测试,但请将此代码放在deleteProject:方法的开头。

if (NO == [sender isKindOfClass:[UIButton class]]) {
    NSLog(@"Oh no, sender isn't a button, it's a %@", [sender class]);
}

答案 1 :(得分:0)

setTitle:forState:

中的资本 S

另外,使用==进行比较,=进行分配。作业总是true

答案 2 :(得分:0)

你错误拼写了UIButton类中的setTitle:forState方法。为方便起见,修正了以下拼写。

 -(IBAction)deleteProject:(id)sender{

    UIButton *button = (UIButton *) sender;
    if (addButton.enabled == YES ) // you could also use if (addButton.enabled)
    {

        addButton.enabled = NO ;

        [button setTitle:@"Back" forState:UIControlStateNormal];

        [mainTableView setEditing:YES animated:YES];
    }

    else // addButton.enabled == NO
    {

        addButton.enabled = YES;

        [button setTitle:@"Delete" forState:UIControlStateNormal];

        [mainTableView setEditing:NO animated:YES];
    }
 }