swift简单的图文混排

class ViewController: UIViewController {

@IBOutlet weak var textLabel: UILabel!

override func viewDidLoad() {

super.viewDidLoad()

let string = "我是一个葱,试试图文混排[abc.png]姓看看[-abc.png-]你人[-wedfweabc.png-]模狗样[abc.png][abc.png]的鬼鬼祟[def.png]祟不:说"

let patter = "\\[.*?\\]"

//        let patter = ":.?,"

let regex = try? NSRegularExpression(pattern: patter, options: [])

let font = UIFont.systemFont(ofSize: 30);

let attMStr = NSMutableAttributedString(string: string, attributes: [NSFontAttributeName:font])

guard let results = regex?.matches(in: string, options: [], range: NSRange(location: 0, length: string.characters.count)) else {

return;

}

if results.count == 0 {

return

}

for i in (0...results.count - 1).reversed(){

let result = results[i]

print(result.range)

let imgName = (string as NSString).substring(with: result.range)

print(imgName)

let attchMent = NSTextAttachment()

attchMent.image = UIImage(named: imgName);

attchMent.bounds = CGRect(x: 0, y: -4, width: textLabel.font.lineHeight, height: textLabel.font.lineHeight)

let attstr = NSAttributedString(attachment: attchMent)

attMStr.replaceCharacters(in: result.range, with: attstr)

}

textLabel.attributedText = attMStr

}

}

你可能感兴趣的:(swift简单的图文混排)