-1

我正在研究 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

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

4

2 回答 2

1

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

因为那个方法在UIButton.

我将如何让它发挥作用?

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

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

请阅读相关文档。

于 2012-11-26T21:23:14.220 回答
0

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

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

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

于 2012-11-26T21:18:41.113 回答