我是 Objective C、XCode iOS 的新手,所以我从一个简单的计数器应用开始。
我已经设置了基础知识(增加按下按钮的分数)但我似乎无法在每次按下按钮时更新 UILabel 文本,即每次我增加 currentScore
它不会更新 UILabel 文本
currentScore
变量
#import "JPViewController.h"
@implementation JPViewController
int currentScore;
- (void)viewDidLoad
{
[super viewDidLoad];
//Init currentScore
currentScore = 0;
NSLog(@"Your score is %d", currentScore);
//Points text label
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 290, 400)];
label.text = [NSString stringWithFormat:@"Your score is: %d", currentScore];
[label setFont:[UIFont boldSystemFontOfSize:16]];
//TODO: Position points in centre.
[self.view addSubview:label];
//Add Points Button
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
[button setTitle:@"Press Me" forState:UIControlStateNormal];
[button sizeToFit];
button.center = CGPointMake(320/2, 60);
[button addTarget:self action:@selector(buttonPressed:)
forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)buttonPressed:(UIButton *)button {
NSLog(@"Button Pressed");
currentScore++;
NSLog(@"Your score is %d", currentScore);
//TODO: Update the label with the new currentScore here.
}
最佳答案
要在按钮旁边使用标签,请执行以下操作
1) 给你的标签打标签
UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 290, 400)];
label.text = [NSString stringWithFormat:@"Your score is: %d", currentScore];
[label setFont:[UIFont boldSystemFontOfSize:16]];
//TODO: Position points in centre.
[label setTag:1000];//Give tag to your label
[self.view addSubview:label];
2) 然后在按钮方法中通过它的标签获取标签
- (void)buttonPressed:(UIButton *)button {
NSLog(@"Button Pressed");
currentScore++;
NSLog(@"Your score is %d", currentScore);
UILabel *label = (UILabel) [self.view viewWithTag:1000]; // you get your label reference here
[label setText:[NSString stringWithFormate:%d,currentScore]]; // then store your current score in your lable
//TODO: Update the label with the new currentScore here.
}
或者这是第二种方法
1) 使您的 UILabel 变量成为全局变量,如下所示
@implementation JPViewController
{
UILabel *label;
}
2) 在viewDidLoad()中
label = [[UILabel alloc]initWithFrame:CGRectMake(100, 100, 290, 400)];
label.text = [NSString stringWithFormat:@"Your score is: %d", currentScore];
[label setFont:[UIFont boldSystemFontOfSize:16]];
//TODO: Position points in centre.
[self.view addSubview:label];
3) 在你的按钮事件中
- (void)buttonPressed:(UIButton *)button {
NSLog(@"Button Pressed");
currentScore++;
NSLog(@"Your score is %d", currentScore);
[label setText:[NSString stringWithFormate:%d,currentScore]]; // then store your current score in your lable
//TODO: Update the label with the new currentScore here.
}
关于ios - 从另一个方法 objective-c 中更新变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29447422/