首先导入所需的库CoreText
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var textLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let string = NSMutableAttributedString.init(string: "The weather is very nice today!")
//进行图文混排
let textAttachment = NSTextAttachment()
textAttachment.image = UIImage.init(named: "1")
//设置图片高度
textAttachment.bounds = CGRect(x: 0,y: 0,width: 100,height: 100)
let textAttachmentString = NSAttributedString.init(attachment: textAttachment)
string.insert(textAttachmentString, at: string.length)
string.insert(textAttachmentString, at: 3)
//let fontRef = Font
//string.addAttribute(NSFontAttributeName, value: fontRef!, range: NSMakeRange(0,3))
//设置字体颜色
string.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSMakeRange(0,3))
//设置字体
string.addAttribute(NSFontAttributeName, value: UIFont.boldSystemFont(ofSize: 20), range: NSMakeRange(0, string.length))
//设置行间距
let settings = NSMutableParagraphStyle()
settings.lineSpacing = 5
string.addAttributes([NSParagraphStyleAttributeName:settings], range: NSMakeRange(0, 2))
textLabel.attributedText = string
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
最后上个效果图