Make selected string of text view Bold, Italic, Un

2019-02-20 18:13发布

问题:

Is there any help to make selected string of text view Bold, Italic, Underline like native "Notes" app of iOS. Please give me helpful links. I am tired of searching for the whole day. Many Thanks.

I have attached my code, to make attributed string Bold and Italic both like native app of iPhone "Notes".

attributedString.beginEditing()
attributedString.addAttributes([NSFontAttributeName: UIFont.boldSystemFont(ofSize: CGFloat(app_delegate.settings.chatFontSize))], range: range)
attributedString.addAttributes([NSFontAttributeName: UIFont.italicSystemFont(ofSize: CGFloat(app_delegate.settings.chatFontSize))], range: range)
attributedString.endEditing()

But its giving only Italic string, not also Bold. I need both Italic and Bold. Thanks.

回答1:

The problem in your code is that you are setting the italic font and overwriting the bold one you've just set. What you need is to use UIFontDescriptor with Symbolic Traits as you can see in this SO answer. So just initialize your system font, get its font descriptor and add traitBold and traitItalic to it. Then you just need to initialize your new Font using UIFont initializer init(descriptor: UIFontDescriptor, size pointSize: CGFloat):

Swift 4 code:

attributedString.beginEditing()
let systemFont: UIFont = .systemFont(ofSize: 32)
if let descriptor = systemFont.fontDescriptor.withSymbolicTraits([.traitBold, .traitItalic]) {
    let systemFontBoldAndItalic = UIFont(descriptor: descriptor, size: 32)
    attributedString.addAttributes([.font: systemFontBoldAndItalic, .underlineStyle: NSUnderlineStyle.styleSingle.rawValue], range: NSRange(location: 0, length: attributedString.string.utf16.count))
}
attributedString.endEditing()


回答2:

Take a look at NSAttributedString. You can use that to create strings that have mixed attributes at different ranges.

In Objective-C, the mutable version, NSMutableAttributedString has methods like setAttributes(_:range:) that let you change the attributes of an attributed string in a specified range.

So you'd initialize an NSMutableAttributedString starting from a normal String object, and then use setAttributes(_:range:) function to set different attributes like Bold, Italic, etc on a range of the string.

(No, I don't have sample code handy.)



回答3:

Although the question is old but it may helps someone.

Using NSMutableAttributedString won't solve the problem, because if you type any where before the customised text the range will be different. Therefore, the customisation will shift to satisfy the updated range. I think using HTML is better solution if you would have a very long string. You may consider using some open source libraries, like ZSSRichTextEditor Hope that help.