Chris
Chris

Reputation: 27394

UILabel - Color specific characters

I have a set of UILabels that are automatically generated by my controller. What I would like is to be able to colour individual characters different colours. How can I achieve this?

Upvotes: 0

Views: 560

Answers (2)

rakeshNS
rakeshNS

Reputation: 4257

You cant make a UILabel with different text colors. You can assign a certain font and certain background color to a UILabel. But you can do one thing. As follows.

  for(int i=0;i<5;i++){
      UILabel *label = [[UILabel alloc]init];
      label.tag = i;
      [self.view addSubView:label];

  }

  for(UIView *view in [self.view subViews]){
  if([view isKindOfClass[UILabel class]]){
  switch (view.tag){
  case 1:

      view.textColor = [UIColor greenColor];
      view.frame = CGRectMake(0,y,37,10);
      (UILabel*)view.text = @"Hello";
      [view sizeToFit];
      y=y+view.frame.size.width;
      break;
  case 2:
      view.textColor = [UIColor redColor];
      view.frame = CGRectMake(0,y,37,10);
      (UILabel*)view.text = @"World";
      [view sizeToFit];
      y=y+view.frame.size.width;
      break;

      //
      //
      }
  }

Upvotes: 0

yuji
yuji

Reputation: 16725

This can't be done with a UILabel. The object usually used to encapsulate strings with formatting is an NSAttributedString, but they can't be displayed by a UILabel.

You'll have to use a CATextLayer instead, or one of a number of drop-in replacements for UILabel that accept attributed strings. See the answers to this question for more details.

Upvotes: 2

Related Questions