iOS编辑UIButton属性

时间:2012-11-26 21:09:16

标签: objective-c ios uibutton

我正在研究iOS开发的基础知识。

到目前为止,我有一个按下按钮,会显示一些文字。但我想要做的是按下它后,我希望它然后更改按钮的文本,到目前为止这就是我所拥有的:

- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//button.backgroundColor = [UIColor redColor];
button.titleLabel.textColor=[UIColor blackColor];
button.frame = CGRectMake(25, 100, 275, 60);
[button setTitle:@"Press this button to reveal the text!" forState:UIControlStateNormal];
[button addTarget:self action:@selector(button_method:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:button];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)button_method:(UIButton *)sender {
NSString *test = @"I am learning Objective-C for the very first time! Also, this is my first ever variable!";
// handle button press
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(25, 25, 275, 60)];
label.text = test;
label.numberOfLines = 0;
label.lineBreakMode = UILineBreakModeWordWrap;
//label.lineBreakMode = NSLineBreakByWordWrapping; //iOS 6 only
[self.view addSubview:label];
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

当我尝试将[button setTitle:@"You pressed the button"];添加到button_method

这不起作用......为什么?我将如何使其发挥作用?

2 个答案:

答案 0 :(得分:1)

  

当我尝试将[button setTitle:@"You pressed the button"];添加到button_method时,它不起作用......为什么?

因为UIButton上不存在该方法。

  

我将如何使其发挥作用?

使用UIButton 实际响应的方法。例如:

[sender setTitle:@"You pressed the button" forState:UIControlStateNormal];

请阅读相关文档。

答案 1 :(得分:0)

您的代码不会更改按钮的标题。但只需添加标签作为视图的子视图。这是你想要的吗?

如果您想更改按钮上的文字,您需要在button_method中执行sender.title.text = test;

我还建议在按钮按下方法中添加NSLog(@"Button pressed");,以便仔细检查是否正在调用它。