Make selected string of text view Bold, Italic, Underline like native “Notes” app of iOS

后端 未结 3 1904
北海茫月
北海茫月 2021-01-16 03:32

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 th

相关标签:
3条回答
  • 2021-01-16 03:44

    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.length))
    }
    attributedString.endEditing()
    
    0 讨论(0)
  • 2021-01-16 03:56

    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.)

    0 讨论(0)
  • 2021-01-16 04:03

    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.

    0 讨论(0)
提交回复
热议问题