使使用 NSTextAttachment 製作包含圖片的字串

使用到兩個物件,皆可置入圖片/連結在字串裡面

NSAttributedString

NSMutableAttributedString

參考文件內容可以發現NSMutableAttributedString 可使用 append 此func
NSAttributedString 卻不行

使用NSMutableAttributedString 存在content變數內,使用NSTextAttachment將圖片存入attachment
使用.bounds(範圍),使圖片限制大小
最後開始寫文章拉!!!!!
最後把label的attributedText設為content就可以顯示包含圖片的文字拉~
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

--

--

Leo 柳
彼得潘的 Swift iOS / Flutter App 開發教室

iOS developer!!I can accept failure but I can’t accept not trying.