您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

讓 UILabel 的文字左右兩端對齊(分散對齊)

編輯:iOS 開發綜合

報紙、雜誌那種左右邊界都齊齊的排版,在 iOS 裡可以透過 NSParagraphStyle 的 NSTextAlignmentJustified 做到。重點是必須用 NSAttributedString,單純設 textAlignment 是沒有效果的。

直接看程式碼:

- (NSAttributedString *)setTextString:(NSString *)text {
    NSMutableAttributedString *mAbStr = [[NSMutableAttributedString alloc] initWithString:text];

    NSMutableParagraphStyle *npgStyle = [[NSMutableParagraphStyle alloc] init];
    npgStyle.alignment = NSTextAlignmentJustified; // 左右兩端對齊
    npgStyle.paragraphSpacing = 11.0;              // 段落間距
    npgStyle.paragraphSpacingBefore = 10.0;        // 段前間距
    npgStyle.firstLineHeadIndent = 0.0;            // 首行縮排
    npgStyle.headIndent = 0.0;                     // 整體縮排

    NSDictionary *dic = @{
        NSForegroundColorAttributeName : [UIColor blackColor],
        NSFontAttributeName : [UIFont systemFontOfSize:15.0],
        NSParagraphStyleAttributeName : npgStyle,
        NSUnderlineStyleAttributeName : [NSNumber numberWithInteger:NSUnderlineStyleNone]
    };

    [mAbStr setAttributes:dic range:NSMakeRange(0, mAbStr.length)];

    NSAttributedString *attrString = [mAbStr copy];
    return attrString;
}

使用方式:

NSString *const msg = @"6日,「幼稚園老師讓帶一條魚」的微博突然間就火了!佔領朋友圈!征服全國網友。圖片甚至遭網友惡搞:水煮魚、生魚片都出來了。1月7日,記者在茫茫人海之中,歷經千辛萬苦終於在浙江慈溪找到了這位被網友吐槽的「粗心」家長!來聽聽他的解釋吧";

self.lbView.attributedText = [self setTextString:msg];

幾個容易忽略的細節

行數限制。分散對齊只在「換行」的行上生效。最後一行不滿一整行時不會被拉開,這是正常行為。如果發現完全沒有效果,先確認文字真的有換行。

numberOfLines。若設定了 numberOfLines 且文字被截斷,最後一行的對齊效果會被省略模式影響。

中英混排的間距。NSTextAlignmentJustified 在純中文上效果最自然;若段落中夾雜大量英文單字或數字,拉開的空白可能會不均勻,這時可以考慮改用 NSKernAttributeName 微調字距。

行距。真正想控制「行與行之間的距離」要用 lineSpacing,而 paragraphSpacing 控制的是「段與段之間」。兩者用途不同,別搞混。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved