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

时间:2011-04-04 18:36:03

标签: iphone xcode ios uilabel settext

我被卡住了:(
在我的应用程序中,每次获得新位置的更新时,我都需要从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]];

}
...

任何想法或帮助?

(这一切都被卡住了所以请原谅我,如果看起来有点傻瓜)我可以提供更多信息。

2 个答案:

答案 0 :(得分:16)

你的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]];

 }

答案 1 :(得分:0)

你是在你的.m文件中合成了标签吗?如果没有,你需要,我相信。