iOS通过NSMutableAttributedString实现图文混排

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
private lazy var textField: UITextView = {
let fontSize: CGFloat = 16
let tv = UITextView()
tv.font = UIFont.systemFont(ofSize: fontSize)
tv.textAlignment = .center
var text = NSMutableAttributedString(string: "一二三四五上山打老虎")
for _ in 1...100 {
let att = NSTextAttachment()
att.image = UIImage(named: "1f601")
att.bounds = CGRect(x: 0, y: tv.font?.descender ?? 0, width: fontSize , height: fontSize)
text.append(NSAttributedString(attachment: att))
}
tv.attributedText = text
return tv
}()
private lazy var textField: UITextView = { let fontSize: CGFloat = 16 let tv = UITextView() tv.font = UIFont.systemFont(ofSize: fontSize) tv.textAlignment = .center var text = NSMutableAttributedString(string: "一二三四五上山打老虎") for _ in 1...100 { let att = NSTextAttachment() att.image = UIImage(named: "1f601") att.bounds = CGRect(x: 0, y: tv.font?.descender ?? 0, width: fontSize , height: fontSize) text.append(NSAttributedString(attachment: att)) } tv.attributedText = text return tv }()
    private lazy var textField: UITextView = {
        let fontSize: CGFloat = 16

        let tv = UITextView()
        tv.font = UIFont.systemFont(ofSize: fontSize)
        tv.textAlignment = .center

        var text = NSMutableAttributedString(string: "一二三四五上山打老虎")
        for _ in 1...100 {
            let att = NSTextAttachment()
            att.image = UIImage(named: "1f601")
            att.bounds = CGRect(x: 0, y: tv.font?.descender ?? 0, width: fontSize , height: fontSize)
            text.append(NSAttributedString(attachment: att))
        }

        tv.attributedText = text
        return tv
    }()

关于对齐的问题tv.font?.descender是关键,具体可参考:http://stackoverflow.com/questions/26105803/center-nstextattachment-image-next-to-single-line-uilabel

这个场景实际就是聊天中的文字+表情混排。

另外要说明下,UITextField(单行输入框)和NSTextAttachment有兼容问题,暂时 没法用这种方法实现。

Leave a Reply

Your email address will not be published. Required fields are marked *