gpt4 book ai didi

iphone - 如何在没有 XIB 文件的情况下以编程方式更新 Xcode 中的 UILabel?

转载 作者:技术小花猫 更新时间:2023-10-29 11:15:52 26 4
gpt4 key购买 nike

我卡住了:(
在我的应用程序中,每次更新到新位置时,我都需要从 CLLocationManager 进行更新。我没有使用 XIB/NIB 文件,我编写的所有代码都是以编程方式完成的。到代码:
.h


@interface TestViewController : UIViewController
UILabel* theLabel;

@property (nonatomic, copy) UILabel* theLabel;

@end

.m


...

-(void)loadView{
....
UILabel* theLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0,0.0,320.0,20.0)];
theLabel.text = @"this is some text";

[self.view addSubView:theLabel];
[theLabel release]; // even if this gets moved to the dealloc method, it changes nothing...
}

- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
NSLog(@"Location: %@", [newLocation description]);

// THIS DOES NOTHING TO CHANGE TEXT FOR ME... HELP??
[self.view.theLabel setText:[NSString stringWithFormat: @"Your Location is: %@", [newLocation description]]];

// THIS DOES NOTHING EITHER ?!?!?!?
self.view.theLabel.text = [NSString stringWithFormat: @"Your Location is: %@", [newLocation description]];

}
...

有任何想法或帮助吗?

(这全是手工卡住的,所以如果看起来有点卡住,请原谅我)如果需要,我可以提供更多信息。

最佳答案

您的 loadView 方法有误。您没有正确设置实例变量,而是生成了一个新的局部变量。通过省略 UILabel * 并将其更改为以下内容,并且不要释放它,因为您希望保留对标签的引用以便稍后设置文本。

-(void)loadView{
....
theLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0,0.0,320.0,20.0)];
theLabel.text = @"this is some text";

[self.view addSubView:theLabel];
}

- (void) dealloc {
[theLabel release];
[super dealloc];
}

然后像这样直接访问变量:

 - (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
NSLog(@"Location: %@", [newLocation description]);

theLabel.text = [NSString stringWithFormat: @"Your Location is: %@", [newLocation description]];

}

关于iphone - 如何在没有 XIB 文件的情况下以编程方式更新 Xcode 中的 UILabel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5542745/

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