富文本能讓同一段文字擁有不同字型、顏色、背景、底線、刪除線、陰影與圖片。以下整理常用 NSAttributedString 屬性。
常用屬性概覽
- NSFontAttributeName:字型與大小。
- NSForegroundColorAttributeName:文字顏色。
- NSBackgroundColorAttributeName:文字背景色。
- NSLigatureAttributeName:連字。
- NSKernAttributeName:字元間距。
- NSStrikethroughStyleAttributeName、NSStrikethroughColorAttributeName:刪除線。
- NSUnderlineStyleAttributeName、NSUnderlineColorAttributeName:底線。
- NSStrokeWidthAttributeName、NSStrokeColorAttributeName:描邊。
- NSShadowAttributeName:陰影。
- NSTextEffectAttributeName:特殊印刷效果。
- NSBaselineOffsetAttributeName:基線偏移。
- NSObliquenessAttributeName、NSExpansionAttributeName:傾斜與伸縮。
- NSVerticalGlyphFormAttributeName:排版方向。
- NSWritingDirectionAttributeName:書寫方向。
- NSLinkAttributeName:超連結。
- NSAttachmentAttributeName:文字附件,常用於圖文混排。
- NSParagraphStyleAttributeName:段落樣式。
字型、顏色與背景
可將文字分段,各自套用不同字型、前景色與背景色,再組合成 NSMutableAttributedString。
連字與字元間距
連字會把特定字母組合顯示為單一圖形;字元間距正值加寬、負值縮窄。
刪除線與底線
可設定單線、粗線、雙線,並自訂顏色。
描邊與空心字
描邊寬度正值通常呈現中空效果,負值則會填滿;若使用空心字,前景色可能失效。
陰影與特殊效果
NSShadow 可設定模糊半徑、顏色與偏移;NSTextEffectLetterpressStyle 可模擬凸版印刷。
基線偏移與價格排版
透過正負偏移,可讓貨幣符號、小數與數字呈現不同高度,適合價格顯示。
傾斜、伸縮與排版方向
可設定文字傾斜、橫向伸縮,以及直排或橫排。iOS 對部分排版值支援有限。
書寫方向
可設定由左至右或由右至左,並可搭配 embedding 或 override。
超連結與附件
NSLinkAttributeName 通常只能搭配 UITextView 使用,並透過代理處理 URL。NSTextAttachment 可把圖片插入文字,實現圖文混排。
掌握這些屬性後,大多數價格、標籤、圖文混排需求都能用原生富文本完成。