UIButton设置多行富文本

2017-07-28  本文已影响1328人  北纬3954

需求:给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 可以根据某个特定的字符将string分割开,但是NSAttributedString没有这个方法(思维误区:NSAttributedString并不是继承自NSString。NSAttributedString有个string属性,可以获取到富文本中的字符串)。

属性字典的属性名称全部在NSAttributedString.h类中。

上一篇下一篇

猜你喜欢

热点阅读