gpt4 book ai didi

ios - 从另一个方法 objective-c 中更新变量

转载 作者:行者123 更新时间:2023-11-28 17:56:17 27 4
gpt4 key购买 nike

我是 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com