是否可以有选择地更改 UITextView 部分的字体?
我有一个 UITextView ,并希望有选择地更改部分字体的大小和样式。例如
Lorem ipsum dolor 坐在el elit lamet,consectetaur cillium adipisicing pecu,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。广告 minim veniam
答案 0 :(得分:2)
您可以使用NSAttributedString
使用addAttribute方法为字符串赋予属性。
let string = "Bold Italics Roman"
let attributes = [NSFontAttributeName: UIFont(name: "Open Sans", size: 18.0)!]
let attributedText = NSMutableAttributedString(string: string, attributes: attributes)
let sampleString = string as NSString
let range = sampleString.range(of: "Italics")
attributedText.addAttribute(NSFontAttributeName, value: UIFont(name: "OpenSans-Italic", size: 18.0)!, range: range)
textView.attributedText = attributedText
答案 1 :(得分:0)
我们可以使用NSString和rangeofString:method
来实现这一点let longString = "Lorem ipsum dolor. VeryLongWord ipsum foobar"
let longestWord = "VeryLongWord"
let longestWordRange = (longString as NSString).rangeOfString(longestWord)
let attributedString = NSMutableAttributedString(string: longString, attributes: [NSFontAttributeName : UIFont.systemFontOfSize(20)])
attributedString.setAttributes([NSFontAttributeName : UIFont.boldSystemFontOfSize(20), NSForegroundColorAttributeName : UIColor.redColor()], range: longestWordRange)
label.attributedText = attributedString