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时

这行不通...为什么?我将如何使其工作?

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

因为该方法在UIButton上不存在。

我将如何使其工作?

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

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

并请阅读相关文档。

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

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

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

最新更新