使使用 NSTextAttachment 製作包含圖片的字串
Published in
6 min readNov 23, 2020
使用到兩個物件,皆可置入圖片/連結在字串裡面
NSAttributedString
NSMutableAttributedString
參考文件內容可以發現NSMutableAttributedString 可使用 append 此func
但 NSAttributedString 卻不行
import UIKitlet content = NSMutableAttributedString(string: "在成為iOS developer! 道路上,一步一")let footAttachment = NSTextAttachment()let rainbowHeart = NSTextAttachment()let NTD = NSTextAttachment()let taiwanMap = NSTextAttachment()let taipei101 = NSTextAttachment()footAttachment.image = UIImage(named: "foot.png")rainbowHeart.image = UIImage(named: "rainbowheart")NTD.image = UIImage(named: "NTD")taipei101.image = UIImage(named: "Taipei101")taiwanMap.image = UIImage(named: "TaiwanMap")footAttachment.bounds = CGRect(x: 0, y: -30, width: 60, height: 60)rainbowHeart.bounds = CGRect(x: 0, y: -30, width: 80, height: 80)NTD.bounds = CGRect(x: 0, y: -35, width: 120, height: 120)taipei101.bounds = CGRect(x: 0, y: -40, width: 60, height: 90)taiwanMap.bounds = CGRect(x: 0, y: -30, width: 80, height: 80)content.append(NSAttributedString(attachment: footAttachment))content.append(NSAttributedString(string: "你不需要很厲害才能開始,但你需要開始才會很厲害,在"))content.append(NSAttributedString(attachment: taiwanMap))content.append(NSAttributedString(string: "這土地上,希望我能成為"))content.append(NSAttributedString(attachment: taipei101))content.append(NSAttributedString(string: "代表台灣這項指標的頂尖iOS developer 賺進大把大把"))content.append(NSAttributedString(attachment:NTD))content.append(NSAttributedString(string: "過著自己嚮往的生活!!!!!!!為此要拿出100倍時間與100倍"))content.append(NSAttributedString(attachment: rainbowHeart))content.append(NSAttributedString(string: "?不!!!是兩百倍的熱忱與時間!!!! 加油!!"))let label = UILabel(frame: CGRect(x: 0, y: 0, width: 300, height: 600))label.numberOfLines = 0label.backgroundColor = .whitelabel.attributedText = content