如何动态更改UILabel文本?

时间:2014-08-17 02:37:17

标签: ios objective-c

我想更改我的UILabel文字。 但是3个标签的文本是相同的,所以我想知道我是否可以做一些事情,比如存储相关UILabel的实例,并写一个通用的字符串格式来改变文本。

所以这些是我的IBOutlet:

@property (strong, nonatomic) IBOutlet UILabel *pushupDetails;
@property (strong, nonatomic) IBOutlet UILabel *situpDetails;
@property (strong, nonatomic) IBOutlet UILabel *runDetails;

这是我希望实现的目标(简化):

-(void)updateDetailText:(NSArray *)results station:(int)station {
  UILabel *templabel;
  switch (station) {
      case 0:
          templabel = [self.pushupDetails mutableCopy];
          break;
      case 1:
          templabel = [self.situpDetails mutableCopy];
          break;
      case 2:
          templabel = [self.runDetails mutableCopy];
          break;
      default:
          break;
  }

  templabel.text = [NSString stringWithFormat:@"You need %d - %d reps", 10, 50];
}

然而,程序崩溃了

 -[UILabel mutableCopyWithZone:]: unrecognized selector sent to instance 0x10b82b920
 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UILabel mutableCopyWithZone:]: unrecognized selector sent to instance 0x10b82b920'

运行mutableCopy的那一刻。是否有可能实现我想要的,或者我是否必须单独编写每个文本更改?

2 个答案:

答案 0 :(得分:0)

您可以为每个标签指定标签0,1和2。

然后改变这样的方法:

-(void)updateDetailText:(NSArray *)results station:(int)station
{    
  ((UILabel *) [self viewWithTag:station]).text = [NSString stringWithFormat:@"You need %d - %d reps", 10, 50];;
}

或者,您可以尝试在每个案例测试中使用通常的作业:

templabel = pushupDetails;

因为你需要引用实际的对象,而不是它的副本。

答案 1 :(得分:0)

UILabel不符合NSCopying课程,因此您无法使用copymutableCopy

你必须使用如下例子

switch (station) {
      case 0:
          templabel = self.pushupDetails;
          break;
      case 1:
          templabel = self.situpDetails;
          break;
      case 2:
          templabel = self.runDetails;
          break;
      default:
          break;
  }
相关问题