我的IBAction已连接到Interface Builder中的按钮。
是否可以在运行期间从我的代码中更改按钮(在IB中)上的文本?
答案 0 :(得分:73)
如果您有一个与代码中的操作相关联的按钮,则可以在没有实例变量的情况下更改标题。
例如,如果按钮设置为此操作:
-(IBAction)startSomething:(id)sender;
您可以在方法中执行此操作:
-(IBAction)startSomething:(id)sender {
[sender setTitle:@"Hello" forState:UIControlStateNormal];
}
或者,如果您想要切换按钮的名称,可以创建名为“buttonToggled”的BOOL
(例如),并以这种方式切换名称:
-(IBAction)toggleButton:(id)sender {
if (!buttonToggled) {
[sender setTitle:@"Something" forState:UIControlStateNormal];
buttonToggled = YES;
}
else {
[sender setTitle:@"Different" forState:UIControlStateNormal];
buttonToggled = NO;
}
}
答案 1 :(得分:19)
UIButton *myButton;
[myButton setTitle:@"My Title" forState:UIControlStateNormal];
[myButton setTitle:@"My Selected Title" forState:UIControlStateSelected];
答案 2 :(得分:5)
是。 UIButton -setTitle:forState:
上有一种方法可以使用它。
答案 3 :(得分:4)
[myButton setTitle:@"Play" forState:UIControlStateNormal];
答案 4 :(得分:4)
另一种切换方式:
- (IBAction)signOnClick:(id)sender
{
if ([_signOnButton.titleLabel.text isEqualToString:@"Sign off"])
{
[sender setTitle:@"Sign on" forState:UIControlStateNormal];
}
else
{
[sender setTitle:@"Sign off" forState:UIControlStateNormal];
}
}
答案 5 :(得分:3)
myapp.h
{
UIButton *myButton;
}
@property (nonatomic,retain)IBoutlet UIButton *myButton;
myapp.m
@synthesize myButton;
-(IBACtion)buttonTitle{
[myButton setTitle:@"Play" forState:UIControlStateNormal];
}
答案 6 :(得分:2)
无需添加if {} else {}控制流。在View或ViewController构造函数中初始化不同状态的按钮文本:
[btnCheckButton setTitle:@"Normal" forState:UIControlStateNormal]; [btnCheckButton setTitle:@"Selected" forState:UIControlStateSelected];
然后将按钮状态切换为Selected:
[btnCheckButton setSelected:YES];
然后将按钮状态切换为“正常”:
[btnCheckButton setSelected:NO];
答案 7 :(得分:0)
迅速5 使用button.setTitle()
@IBOutlet weak var button: UIButton!
setTitle
和文本和状态。 button.setTitle("Button text here", forState: .normal)