【问题标题】:How to update a UILabel in Xcode programmatically without XIB files?如何在没有 XIB 文件的情况下以编程方式更新 Xcode 中的 UILabel?
【发布时间】:2011-07-29 09:40:07
【问题描述】:

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

}
...

有什么想法或帮助吗?

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

【问题讨论】:

  • NSLog 是否显示正确的位置?
  • @Radek 我放到loadView里面,UILabel应该放到viewDidLoad里面吗?那是超越点吗?为什么这会使 UILabel 可变
  • 在 UIViewController 中使用 loadView 以编程方式创建用户界面是可以的。但是你是对的,如果你想引用 IBOutlets,你会使用 viewDidLoad 方法来确保 XIB 已经加载并且所有的 outlet 都已经可用。

标签: iphone xcode ios uilabel settext


【解决方案1】:

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

 }

【讨论】:

  • 我仍然得到原始文本“这是一些文本”,它永远不会更新,即使我可以在控制台中看到打印有新位置的 NSLog 输出。
  • 我更新了答案。我认为您在位置管理器委托回调中引用的 theLabel 实例变量仍然为零,因为您必须正确分配它。
  • 你是对的,它必须是一个本地变量......你可以更改上面的代码并删除带有注释的 [theLabel release],因为那样会发布得太早(即在回答)谢谢,你摇滚!
  • 对,我用粗体写了不要发布 ivar,我复制了你的代码并发布了它。多么尴尬...我更正了代码。不客气。
【解决方案2】:

您是否正在合成 .m 文件中的标签...?如果没有,我相信你需要这样做。

【讨论】:

  • 如果getter和setter没有实现,并且没有给出@synthesize,编译器会给出警告。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多