swift——富文字文字的簡單使用

b10l07發表於2017-03-29

  如果需要一個字元前後文字顏色不一樣,也就是說一個字串分成多個部分,每個部分的屬性(顏色,字型,大小等)不一樣,那就是富文字文字 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])


5276080-1392e75b5f018129.png
程式碼圖

效果圖:



5276080-c41925b1a087b64c.png
效果圖




轉載請註明出處,謝謝。

相關文章