目标C中的UILabel文本的多个属性(不同的文本大小,字体和偏移)

时间:2016-04-25 13:33:49

标签: ios objective-c uilabel

  

我想做类似的事情:

enter image description here

  

文本不固定,会在运行时更改。

需要你的想法!

提前致谢!

1 个答案:

答案 0 :(得分:3)

  

经过大量搜索,我最终得到了

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    previousRandom = -1;

    // NEEDY TALL BORING COOL CHEAP AWESOME HANDSOME SEXY SMART SMELLY
    NSString *strForText = @"NEEDY  TALL  BORING  COOL  CHEAP  AWESOME  HANDSOME  SEXY  SMART  SMELLY  HAPPY  RICH  FUNNY  SEXY  SMART  SMELLY  HAPPY  RICH  FUNNY";

    self.labelForText.attributedText = [[NSAttributedString alloc]initWithString:strForText];

    NSArray *arrayForText = [self.labelForText.text componentsSeparatedByString:@" "];

    for (NSString *str in arrayForText) {

        [self makeTextRandmolyFocused:self.labelForText andString:str];
    }

}

// making the $ prefix
-(void)makeTextRandmolyFocused:(UILabel *)label andString:(NSString *)subString {

    NSRange range = [label.text rangeOfString:subString];

    NSArray *arrayForFontSize = @[@"18",@"11",@"16",@"13",@"14",@"20"];
    NSArray *arrayForFontName = @[@"HelveticaNeue-Medium",@"HelveticaNeue-Light",@"HelveticaNeue-Bold",@"HelveticaNeue-Medium",@"HelveticaNeue-Medium",@"HelveticaNeue-Bold"];
    NSArray *arrayForBaselineOffset =  @[@"2.3",@"1.2",@"2.5",@"1.5",@"3.5",@"0"];

    int randomPosition;

    do {
        randomPosition = arc4random_uniform(5);
    } while (randomPosition == previousRandom);

    previousRandom = randomPosition;

    NSNumber *baselineOffSet =[NSNumber numberWithUnsignedInteger:[arrayForBaselineOffset[randomPosition] integerValue]];

    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setLineSpacing:3.0];
    [style setAlignment:NSTextAlignmentCenter];

    float spacing = 2.5f;


    NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:label.attributedText];

    [attributedText setAttributes:@{
                                    NSFontAttributeName:[UIFont fontWithName:arrayForFontName[randomPosition] size:[arrayForFontSize[randomPosition] floatValue]],
                                    NSBaselineOffsetAttributeName:baselineOffSet,
                                    NSParagraphStyleAttributeName:style,
                                    NSKernAttributeName:@(spacing)
                                    }
                            range:range];

    label.attributedText = attributedText;

}
  

其中输出为:

enter image description here