swift 富文字文字的簡單使用

2021-09-24 07:10:43 字數 1716 閱讀 6100

如果需要乙個字元前後文字顏色不一樣,也就是說乙個字串分成多個部分,每個部分的屬性(顏色,字型,大小等)不一樣,那就是富文字文字 nsmutableattributedstring

直接上**了

let str = "今宵杯中映著明月 物華天寶人傑地靈"

let attrstr = nsmutableattributedstring.init(string: str)

attrstr.addattribute(nsattributedstringkey.foregroundcolor, value:uicolor.orange, range:nsrange.init(location:0, length: 8))

attrstr.addattribute(nsattributedstringkey.foregroundcolor, value:uicolor.red, range:nsrange.init(location:9, length: 8))

label1.attributedtext = attrstr

/// 僅字型和大小

label2.attributedtext = nsattributedstring.init(string:"這是一串文字", attributes: [nsattributedstringkey.backgroundcolor:uicolor.cyan, nsattributedstringkey.font:uifont.systemfont(ofsize:28)])

/// 背景色

label3.attributedtext = nsattributedstring.init(string:"這是乙個有背景色的文字", attributes: [nsattributedstringkey.backgroundcolor:uicolor.green, nsattributedstringkey.font:uifont.systemfont(ofsize:18)])

/// 陰影

let shadow = nsshadow.init()

shadow.shadowcolor = uicolor.red

shadow.shadowoffset = cgsize.init(width: 2, height: 2)

label4.attributedtext = nsattributedstring.init(string:"這是乙個有陰影的文字", attributes: [nsattributedstringkey.foregroundcolor:uicolor.red, nsattributedstringkey.font:uifont.systemfont(ofsize:18), nsattributedstringkey.shadow: shadow])

/// 下劃線

label5.attributedtext = nsattributedstring.init(string:"這是乙個有下劃線的文字", attributes: [nsattributedstringkey.foregroundcolor:uicolor.purple, nsattributedstringkey.font:uifont.systemfont(ofsize:18), nsattributedstringkey.underlinestyle:nsunderlinestyle.stylesingle.rawvalue])

複製**

效果圖:

iOS 富文字簡單使用

uitextview uptext uitextview alloc init uptext.font uifont systemfontofsize 14.f uptext.backgroundcolor uicolor clearcolor uptext.textcolor uicolor wh...

富文字的使用

一,理解 對於以前,我們用label進行新增文字的時候,只是在 label的本身上新增,從來沒有考慮過其他的方式,今天呢,由於我看了別人的一片技術部落格,有感所以就記錄了下來,希望能夠幫助到那些有需要的人 不帶段落分析的 如下 nsstring str 也許我們的心裡藏有乙個海洋,流出來的卻是兩行清...

簡化富文字的使用

簡化富文字的使用 1.如果不進行任何的封裝,直接使用富文字會破壞可讀性,可讀性極差 2.本例子提供了維護性較強的封裝 3.本人僅僅實現了兩種富文字的例項 設定文字字型以及文字屬性 剩下的可以參考本人的實現來進行擴充套件 4.每一種富文字屬性都應該抽象成乙個類,而通過統一的介面進行管理 本例子中,僅僅...