#34 利用 NSTextAttachment 製作包含圖片的字串之我要吃好料的
Published in
Nov 19, 2020
目的
利用NSAttributedString/NSTextAttachment實現label上顯示圖片與文字
作法
先從以下網站去抓台灣特有emoji
這邊有使用到兩個物件,皆可置入圖片/連結在字串裡面
NSAttributedString
NSMutableAttributedString
這裡使用NSMutableAttributedString是因為我們需要繼續變動content2的內容(只有NSMutableAttributedString有append function可以用)
let content2 = NSMutableAttributedString(string: "把把說只要我英文考")
首先建立一個字串出來後,使用NSTextAttachment將圖片存入attachment裡面
let eightySevenAttachment = NSTextAttachment()eightySevenAttachment.image = UIImage(named: "87_Points_128x128.png")eightySevenAttachment.bounds = CGRect(x: 0, y: -5, width: 30, height: 30)content2.append(NSAttributedString(attachment: eightySevenAttachment))content2.append(NSAttributedString(string: "分,就會帶我去鼎泰豐吃"))
這裡要用.bounds來限制eightySevenAttachment的大小,不然會變下圖這樣
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 200))label.numberOfLines = 0label.backgroundColor = UIColor.whitelabel.attributedText = content2
後記
之前是先做99乘法表有印象使用到,原來在這裏就有教基本使用技巧
Reference