Swift UIlabel 的高級用法,文本顯示錶情,圖片

可以定義一個UIlabel的擴展代碼如下

class CPSPFMarkLabel: UILabel {

    convenience init(text: String) {
        self.init(frame:CGRect.zero)
        
        let markLabelText = " 清明時節雨紛紛☺" + text
        self.textAlignment = .center
        self.textColor = UIConstants.AppFontColor
        self.font = UIConstants.DefaultFont15
        self.backgroundColor = UIConstants.AppWhiteColor
        let markAttribute = NSMutableAttributedString(string: markLabelText)
        markAttribute.addAttribute(NSAttributedStringKey.foregroundColor, value:UIConstants.AppRedColor, range: NSRange(location: 6,length: text.count))
        //以上是富文本顯示
        let arkattch = NSTextAttachment() //定義一個attachment
        markattch.image = UIImage(named: "image_timing")//初始化圖片
        markattch.bounds = CGRect(x: 0, y: -1, width: 15, height: 15) //初始化圖片的 bounds
        let markattchStr = NSAttributedString(attachment: markattch) // 將attachment  加入富文本中
        markAttribute.insert(markattchStr, at: 0)// 將markattchStr  加入原有文字的某個位置
        self.attributedText = markAttribute
    }
}

image

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章