最近项目使用swift需要用到富文本,网上搜都是OC的或者swift2的,不多说直接上
Swift4.0:
- 此方法适用于textFiled的占位字符
- textView
- UILabel
- 按钮需要文字的地方都可以
先看效果
00E18D8B-679D-40B2-89B8-DCB72D645048.png
在上代码
func FuWenBen() -> NSMutableAttributedString {
//定义富文本即有格式的字符串
let attributedStrM : NSMutableAttributedString = NSMutableAttributedString()
// 左上角星星
let xingxing = NSAttributedString.init(string: "*", attributes: [NSAttributedStringKey.backgroundColor : UIColor.black , NSAttributedStringKey.foregroundColor : UIColor.red , NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 20) ,NSAttributedStringKey.baselineOffset : (20)])
let wo = NSAttributedString.init(string: "我", attributes: [NSAttributedStringKey.backgroundColor : UIColor.gray , NSAttributedStringKey.foregroundColor : UIColor.green , NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 30)])
let shi : NSAttributedString = NSAttributedString(string: "是", attributes: [NSAttributedStringKey.foregroundColor : UIColor.purple, NSAttributedStringKey.font : UIFont.systemFont(ofSize: 12)])
//帅逼
let shuaibi : NSAttributedString = NSAttributedString(string: "帅逼", attributes: [NSAttributedStringKey.foregroundColor : UIColor.lightGray, NSAttributedStringKey.font : UIFont.systemFont(ofSize: 38)])
//图片
let smileImage = UIImage.init(named: "ic_avarta")
let textAttachment : NSTextAttachment = NSTextAttachment()
textAttachment.image = smileImage
textAttachment.bounds = CGRect(x: 0, y: -4, width: 22, height: 22)
attributedStrM.append(xingxing)
attributedStrM.append(wo)
attributedStrM.append(shi)
attributedStrM.append(shuaibi)
attributedStrM.append(NSAttributedString(attachment: textAttachment))
return attributedStrM
}
网友评论