如何为标签中的每个单词(从服务器获取动态单词)设置不同的颜色?

时间:2017-06-06 09:26:42

标签: ios objective-c iphone

我在数组中有多个单词:

NSMutableArray * array = [[NSMutableArray alloc] initWithObjects:@"1 ball",@"2 ball",@"3 ball",@"4 ball", nil];

我需要将这些单词设置为UILabel,颜色不同。

2 个答案:

答案 0 :(得分:2)

@Hari你可以尝试下面的代码

 NSMutableArray * array = [[NSMutableArray alloc] initWithObjects:@"1 ball",@"2 ball",@"3 ball",@"4 ball", nil];

NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] init];
for (NSString * str in array)
 {
        NSMutableAttributedString * textstr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ ,",str] attributes:@{NSForegroundColorAttributeName :[self getRandomColor]}];
        [attStr appendAttributedString:textstr];
 }

UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(10, 300, 300, 30)];
lab.attributedText = attStr;
[self.view addSubview:lab];



-(UIColor *) getRandomColor
{
    CGFloat redcolor = arc4random() % 255 / 255.0;
    CGFloat greencolor = arc4random() % 255 / 255.0;
    CGFloat bluencolor = arc4random() % 255 / 255.0;
    return  [UIColor colorWithRed:redcolor green:greencolor blue:bluencolor alpha:1.0];
}

答案 1 :(得分:2)

对于Swift,您可以使用以下代码。

import UIKit
var str = ["Hi", "Hello", "I", "am", "Prabhu"]
var newStr : [NSAttributedString] = []
var newS = NSMutableAttributedString()

func getRandomColor() -> UIColor{
  let randomRed:CGFloat = CGFloat(drand48())
  let randomGreen:CGFloat = CGFloat(drand48())
  let randomBlue:CGFloat = CGFloat(drand48())
  return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
}

for s in str {
  let newString = NSMutableAttributedString.init(string: s + ",", attributes: [NSForegroundColorAttributeName : getRandomColor()])
  newS.append(newString)
}

print(newS)