iOS- 設置label的行間距&字體間距

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *content = @"好嗎 一句話就哽住了喉 城市當背景的海市蜃樓 我們像分隔成一整個宇宙 再見都化作烏有 我們說好決不放開相互牽的手 可現實說過有愛還不夠走到分岔的路口 你向左我向右 我們都倔強地不曾回頭 我們說好就算分開一樣做朋友 時間說我們從此不可能再問候 人群中再次邂逅";

    NSMutableDictionary *attDic = [NSMutableDictionary dictionary];
    [attDic setValue:[UIFont systemFontOfSize:16] forKey:NSFontAttributeName];      // 字體大小
    [attDic setValue:[UIColor redColor] forKey:NSForegroundColorAttributeName];     // 字體顏色
    [attDic setValue:@5 forKey:NSKernAttributeName];                                // 字間距
    [attDic setValue:[UIColor cyanColor] forKey:NSBackgroundColorAttributeName];    // 設置字體背景色
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:content attributes:attDic];
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 20;                                                          // 設置行之間的間距
    [attStr addAttribute:NSParagraphStyleAttributeName value:style range: NSMakeRange(0, content.length)];
    
    CGFloat contentH = [attStr boundingRectWithSize:CGSizeMake(200, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size.height;                                                    // 自動計算文本高度
    UILabel *txtLbl = [[UILabel alloc] init];
    txtLbl.frame = CGRectMake(100, 100, 200, contentH);
    txtLbl.numberOfLines = 0;
    txtLbl.attributedText = attStr;
    txtLbl.backgroundColor = [UIColor redColor];
    
    [self.view addSubview:txtLbl];  
}

效果圖:

img.png

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容