正确返回iOS uilabel方法的方法



我正在用一种称为displayTemp

的方法创建一个uilabel
- (UILabel *) displayTemp
{
_tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 240, 300, 30)];
[self.view addSubview:_tempLabel];
NSDictionary *key = [self.getAPICall objectForKey:@"currently"];
_tempLabel.text = [key objectForKey:@"temperature"];
return _tempLabel;
}

这只是从API调用中带回一个值。

我想在ViewDidload方法中显示Dis Uilabel及其文本

- (void)viewDidLoad
{
self.view.backgroundColor = [UIColor colorWithRed:0.976 green:0.518 blue:0.439 alpha:1];
UILabel *getTemp = self.displayTemp;
//How do I return the text property of self.DisplayTemp
}

然后我将如何返回?有更好的方法吗?

您在这里混合成语。而不是这样做" @property"类型的事情:

UILabel *getTemp = self.displayTemp;

将该行更改为:

[self displayTemp];

在您的" viewDidLoad"方法中,您会没事的。您无需从displayTemp方法返回uilabel对象,因为您已经将其添加到视图控制器的视图中。

UILabel *getTemp = [self displayTemp];
getTemp.text

此外, @michaeldautermann的答案,我建议您使用条件分支(如果)在-(UILabel *)displayTemp方法中仅创建uilabel。尽管该方法仅一次由-(void)viewDidLoad调用,但就课堂架构而言,您最好使该方法更加灵活,安全地针对多个调用。

因此,我修改了该方法如下:

- (UILabel *) displayTemp
{
   if (_tempLabel == nil) {
       _tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 240, 300, 30)];
       NSDictionary *key = [self.getAPICall objectForKey:@"currently"];
      _tempLabel.text = [key objectForKey:@"temperature"];
       [self.view addSubview:_tempLabel];
   }
  return _tempLabel;
}

我希望我的建议对您有用。

最新更新