Center two fonts with different different sizes vertically in an NSAttributedString

后端 未结 4 2003
一生所求
一生所求 2020-12-24 10:13

I use NSAttributedString to generate a string with two different sizes. By default, its bottom alignment looks like this:

4条回答
  •  無奈伤痛
    2020-12-24 10:59

    Here is a working example to vertically align smaller text using NSBaselineOffsetAttributeName.

    NSString *bigString   = @"BIG";
    NSString *smallString = @"Small String";
    NSString *fullString = [NSString stringWithFormat:@"%@ %@", bigString, smallString];
    
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:fullString];
    
    NSRange bigStringRange = NSMakeRange(0, bigString.length);
    NSRange smallStringRange = NSMakeRange(bigStringRange.length, smallString.length);
    
    [string beginEditing];
    
    
    //Set big string font and size
    [string addAttribute:NSFontAttributeName
                   value:[UIFont systemFontOfSize:28.0]
                   range:bigStringRange];
    
    //set small string font and size
    [string addAttribute:NSFontAttributeName
                   value:[UIFont systemFontOfSize:18.0]
                   range:smallStringRange];
    
    //Set small string baseline offset
    [string addAttribute:NSBaselineOffsetAttributeName
                   value:[NSNumber numberWithFloat:3.0]  //adjust this number till text appears to be centered
                   range:smallStringRange];
    
    [string endEditing];
    

提交回复
热议问题