Xcode - 如何获取按钮以多次更改标签文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12964719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Xcode - How to get button to change label text multiple times
提问by user1757682
I am trying to have numbers change by different amounts, by the press of one button. I am new to xcode and do not know how to do this, any help would be nice.
我试图通过按一个按钮来改变不同数量的数字。我是 xcode 的新手,不知道该怎么做,任何帮助都会很好。
I want the number to change to 15, but only when I press the button for a second time. Then, I would like, upon a third press, for the number to change 30. press 1: from "0" to "5", press 2: from "5" to "15", press 3: from "15" to 30", I want to learn how to add different amounts
我希望数字更改为 15,但只有在我第二次按下按钮时才会更改。然后,我想在第三次按下时将数字更改为 30。按 1:从“0”到“5”,按 2:从“5”到“15”,按 3:从“15”到30", 我想学习如何添加不同的数量
-(IBAction)changep1:(id) sender {
p1score.text = @"5";
if (p1score.text = @"5"){
p1score.text = @"15";
//Even if the above worked, I do not know how I would write the code to change it to 30. }
//即使上面的方法有效,我也不知道如何编写代码将其更改为 30。}
回答by Beltalowda
It sounds like you probably want to add a property to your view controller to store Player 1's score, something like this:
听起来您可能想向视图控制器添加一个属性来存储玩家 1 的分数,如下所示:
@property (nonatomic, assign) NSInteger p1Score;
Then in your init
method, you can give this property an initial value:
然后在你的init
方法中,你可以给这个属性一个初始值:
self.p1Score = 0; // you can set this to any integral value you want
Then, in your button tap method (changep1
) you can do something like this:
然后,在您的按钮点击方法 ( changep1
) 中,您可以执行以下操作:
- (IBAction)changep1:(id)sender
{
// add 5 (or any value you want) to p1Score
self.p1Score = self.p1Score + 5;
// update the display text. in code below %d is replaced with the value of self.p1Score
p1score.text = [NSString stringWithFormat:@"%d", self.p1Score];
}