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

后端 未结 3 1908
北海茫月
北海茫月 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()
    

提交回复
热议问题