作業5#利用 NSTextAttachment 製作包含圖片的字串

練習利用 NSAttributedString 和 NSTextAttachment,label 就能排出包含美麗圖片的文字。

可愛的台灣 emoji 圖片下載連結。

1.將圖片加到 playground

2.產生 NSMutableAttributedString 物件。

只有 NSAttributedString 可以包含圖片,因此生成可以改變的 NSMutableAttributedString。

let content = NSMutableAttributedString(string: "為了兒子的健康,只好每天煮飯")

3.產生包含電鍋圖片的 NSTextAttachment 物件。

NSTextAttachment 可以包含圖片,之後我們將利用它生成包含圖片的 NSAttributedString。

let electricPotAttachment = NSTextAttachment()electricPotAttachment.image = UIImage(named: "Tatung_s_Rice_cooker_128x128")

4.生成 NSAttributedString 時傳入 electricPotAttachment,產生包含圖片的文字,然後將它加到 content 上。

content.append(NSAttributedString(attachment:electricPotAttachment))

5.將 label 的 attributedText 設為 content,顯示包含圖片的文字。

label.attributedText = content

6.設定 NSTextAttachment 的大小位置。

bounds 的 y > 0 將讓圖片往上移動,y < 0 則往下移動

electricPotAttachment.bounds = CGRect(x: 0, y: -5, width: 30, height: 30)

完整程式

--

--