參考文章
主要步驟:
- 將可愛 emoji 圖檔拖曳至 Xcode 的 Resources 資料夾下(圖檔要直接在Resources 下,不能再多一層檔案夾)
- 把 NSMutableAttributedString 物件傳入存放所有內容的常數 content中
- 把 NSTextAttachment 物件存入放emoji的常數中
- 把 UIImage 圖檔存入常數
- 設定圖片的位置、大小
- 生成 NSAttributedString 時把把放 emoji 的常數傳入 content
- 定義一個放文字的常數,並把UILabel傳入,設定顯示所有文字的範圍大小行數,並將 content 傳入
import UIKitlet content = NSMutableAttributedString(string: "從小會")let BopomofoAttachment = NSTextAttachment()BopomofoAttachment.image = UIImage(named: "Bopomofo_128x128.png")content.append(NSAttributedString(attachment: BopomofoAttachment))BopomofoAttachment.bounds = CGRect(x: 0, y: -5, width: 30, height: 30)content.append(NSAttributedString(string: "的時候最愛喝"))let BubbleTeaAttachment = NSTextAttachment()BubbleTeaAttachment.image = UIImage(named: "Bubble_Tea_128x128")content.append(NSAttributedString(attachment: BubbleTeaAttachment))BubbleTeaAttachment.bounds = CGRect(x: 0, y: -5, width: 30, height: 30)content.append(NSAttributedString(string: "最愛的東西是"))let XiaolongbaoAttachment = NSTextAttachment()XiaolongbaoAttachment.image = UIImage(named: "Xiaolongbao_128x128")content.append(NSAttributedString(attachment: XiaolongbaoAttachment))XiaolongbaoAttachment.bounds = CGRect(x: 0, y: -5, width: 30, height: 30)content.append(NSAttributedString(string: "偶爾會和出門總是拿著"))let TricolorBagAttachment = NSTextAttachment()TricolorBagAttachment.image = UIImage(named: "Tricolor_Bag_128x128")content.append(NSAttributedString(attachment: TricolorBagAttachment))TricolorBagAttachment.bounds = CGRect(x: 0, y: -5, width: 30, height: 30)content.append(NSAttributedString(string: "的朋友在"))let Taipei101Attachment = NSTextAttachment()Taipei101Attachment.image = UIImage(named: "Taipei_101_128x128")content.append(NSAttributedString(attachment: Taipei101Attachment))Taipei101Attachment.bounds = CGRect(x: 0, y: -5, width: 30, height: 30)content.append(NSAttributedString(string: "喝著台灣"))let TaiwanBeerAttachment = NSTextAttachment()TaiwanBeerAttachment.image = UIImage(named: "Taiwan_Beer_128x128")content.append(NSAttributedString(attachment: TaiwanBeerAttachment))TaiwanBeerAttachment.bounds = CGRect(x: 0, y: -5, width: 30, height: 30)content.append(NSAttributedString(string: "再配著"))let PineappleCakeAttachment = NSTextAttachment()PineappleCakeAttachment.image = UIImage(named: "Pineapple_Cake_128x128")content.append(NSAttributedString(attachment: PineappleCakeAttachment))PineappleCakeAttachment.bounds = CGRect(x: 0, y: -5, width: 30, height: 30)let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 200))label.numberOfLines = 0label.attributedText = content