要學習圖文混排首先要了解AttributedString
屬性,AttributedString
分為NSMutableAttributedString
和NSAttributedString
。它是一個管理字符串以及與該字符串中的單個字符或某些范圍的字符串相關的屬性。通常這個屬性我們可以控制字符串的字體樣式、大小、顏色、背景色、行距、字距、段落、下劃線、刪除線、文本附件等等。
有此屬性的控件有UILabel
、UITextField
和UITextView
,今天通過設置UILabel
的AttributedString
屬性來學習一下如何進行簡單的圖文混排。比較簡單,就直接貼出代碼:
class UILabelViewController: UIViewController {
@IBOutlet weak var contentLabel: UILabel!
let contentString = "作者寫在書后:時間是2003年或2004年,季節可能是夏末也可能是秋初。\n詳細的時間和季節記不清了,只記得我一個人在午后的北京街頭閑逛,碰到一群大學生,約二十個,男女都有,在路旁樹蔭下一米高左右的矮墻上坐成一列。\n他們悠閑地晃動雙腿,談笑聲此起彼落。我從他們面前走過,不禁想起過去也曾擁有類似的青春。\n………"
override func viewDidLoad() {
super.viewDidLoad()
// 創建富文本字符串
let attributedText = NSMutableAttributedString(string: contentString)
// 圖片附件
let imageAttachment = NSTextAttachment()
let image = UIImage(named: "nuannuan0.jpg")
imageAttachment.image = image
// 設置圖片顯示的寬度和 UILabel 的寬度一致
let imageWidth = contentLabel.frame.width
let imageHeight = image!.size.height / image!.size.width * imageWidth
imageAttachment.bounds = CGRect(x: 0, y: 0, width: imageWidth, height: imageHeight)
// 將帶圖片附件的富文本字符串插入到指定位置
attributedText.insert(NSAttributedString(attachment: imageAttachment), at: 7)
contentLabel.attributedText = attributedText
}
}
Paste_Image.png