更改UIButton文本

Jul*_*tea 98 xcode objective-c event-handling uibutton ios

所以当我点击它时,我正在尝试更新UIButton上的文本.我正在使用以下行来更改文本:

calibrationButton.titleLabel.text = @"Calibration";
Run Code Online (Sandbox Code Playgroud)

我已经确认文本正在更改,但是当我运行应用程序并单击按钮时,它会在一瞬间更改为"校准",然后再返回其默认值.任何想法为什么会这样?我需要调用某种刷新功能吗?

Jes*_*mpo 242

在布置其子视图时,UIButton将使用其自己的标题值设置其titleLabel的文本值,以便您可以为四种状态(正常,突出显示,选定,禁用)设置最多四个不同的字符串.

由于此功能,直接设置titleLabel的文本将不会保留,并且在布局其子视图时将由按钮重置.

这是您需要更改按钮状态的标题文本.

[calibrationButton setTitle:@"Calibration" forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

  • 那么button.titleLabel.text = @"某些文字"应该是什么呢? (4认同)
  • @BorisGafurov如果输入`button.titleLabel`,您会看到titleLabel是一个只读属性,因此任何只读属性的属性也是只读的.使用点符号编辑它们将不起作用,因此您需要显式方法来编辑它们.这至少对我有意义. (4认同)
  • @erdekhayser实际上,只读属性**CAN**具有读/写属性.我使用titlelabel的标签将一个整数传递给一个动作方法.另见Apple的文档[链接](https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UIButton_Class/index.html#//apple_ref/occ/instp/UIButton/titleLabel)`虽然此属性是只读的,其自身的属性是可读/写的.主要使用这些属性来配置按钮的文本.例如:` (3认同)

Ash*_*lls 33

要设置按钮文本,请使用以下方法:

[calibrationButton setTitle: @"Calibration" forState: UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

有关UIButton详细信息,请参阅课程参考... http://developer.apple.com/library/ios/#documentation/uikit/reference/UIButton_Class/UIButton/UIButton.html

或者在Swift 3中:

calibrationButton.setTitle("Calibration", for: .normal)
Run Code Online (Sandbox Code Playgroud)


bha*_*191 5

以编程方式,你可以设置如下的按钮标题:

[myButton setTitle:@"buttonTitle" forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

您还可以从故事板设置按钮标题属性.