如何切换 UIFont 的粗体和斜体

How to toggle Bold and Italic of UIFont

我正在尝试在 swift.

中使用 textKit 将粗体和斜体应用到 UITextView 中的 selected 文本

这是代码:

let isBold = false

if !isActive(modification: .swapBoldWithItalic) || isBold{
    storage.setAttributes(attributes, range: range)
} else {
    let currentFont = attributes![.font] as? UIFont
    
    let fontDescriptor = currentFont?.fontDescriptor
    
    var changedFontDescriptor: UIFontDescriptor?
    
    if fontDescriptor!.symbolicTraits.contains(.traitItalic) {
        changedFontDescriptor = fontDescriptor?.withSymbolicTraits(fontDescriptor!.symbolicTraits.union(.traitItalic))
        
    } else {
        changedFontDescriptor = fontDescriptor?.withSymbolicTraits(fontDescriptor!.symbolicTraits.union(.traitBold))
        
    }
    
    
    var updatedFont: UIFont? = nil
    if let changedFontDescriptor = changedFontDescriptor {
        updatedFont = UIFont(descriptor: changedFontDescriptor, size: (currentFont?.pointSize)!)
        
    }
    let dict = [
        NSAttributedString.Key.font: updatedFont,
        NSAttributedString.Key.foregroundColor: UIColor.red
    ]
    
    storage.setAttributes(dict, range: range)
}

我想要实现的是

现在发生的事情是,当我 select 文本并将其更改为粗体时,它变为粗体,但是当我尝试将另一个文本更改为斜体时,它也变为粗体,但我仍然无法从粗体换成斜体。

我怀疑您想通过不同的按钮切换粗体和斜体。我做了一个扩展,你可以很容易地使用它:

extension UIFont {
    func byTogglingSymbolicTraits(_ symbolicTraits: UIFontDescriptor.SymbolicTraits) -> UIFont {
        UIFont(
            descriptor: fontDescriptor.byTogglingSymbolicTraits(symbolicTraits),
            size: pointSize
        )
    }
}

extension UIFontDescriptor {
    func byTogglingSymbolicTraits(_ traints: UIFontDescriptor.SymbolicTraits) -> UIFontDescriptor {
        if symbolicTraits.contains(traints) {
            return withSymbolicTraits(symbolicTraits.subtracting(traints))!
        } else {
            return withSymbolicTraits(symbolicTraits.union(traints))!
        }
    }
}

用法:

font = font.byTogglingSymbolicTraits(.traitBold)
// or
font = font.byTogglingSymbolicTraits(.traitItalic)