需求:給UIbutton設置兩行文字,兩行文字字體顏色各不相同。兩行文字均水平居中。

Glass.png
NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n",@"第一行文字"] attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20], NSForegroundColorAttributeName:[UIColor blueColor]}];
NSAttributedString *time = [[NSAttributedString alloc] initWithString:@"第二行" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:40],NSForegroundColorAttributeName:[UIColor blackColor]}];
[title appendAttributedString:time];
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
[paraStyle setLineSpacing:10];
paraStyle.alignment = NSTextAlignmentCenter;
[title addAttributes:@{NSParagraphStyleAttributeName:paraStyle} range:NSMakeRange(0, title.length)];
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 100, 375, 300)];
btn.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
[btn setAttributedTitle:title forState:UIControlStateNormal];
NSString *string = @"之二噶山東干嘛干嘛沒代溝按摩棒\n嘎嘎繳納低昂";
NSArray *array = [string componentsSeparatedByString:@"\n"];
NSAttributedString * attString = [[NSAttributedString alloc] initWithString:@"耐煩地\n愛國迪迦奧is機動工愛的"];
NSRange range = [attString.string rangeOfString:@"\n"];
NSAttributedString *component = [attString attributedSubstringFromRange:NSMakeRange(0, range.location)];
NSString 可以根據(jù)某個特定的字符將string分割開,但是NSAttributedString沒有這個方法(思維誤區(qū):NSAttributedString并不是繼承自NSString。NSAttributedString有個string屬性,可以獲取到富文本中的字符串)。
屬性字典的屬性名稱全部在NSAttributedString.h類中。