可可:当我加粗我的NSTextview并加下划线时,它不再加粗

问题描述 投票:0回答:1

我有一个加粗按钮,下划线按钮和一个NSTextview。当我加粗文本,然后使用下划线时,粗体就会出现。

这是我的粗体按钮代码

@IBAction func boldBTN(_ sender: Any) {
    if let font = textView.textStorage?.attributes(at: textView.selectedRange.location, longestEffectiveRange: nil, in: textView.selectedRange)[.font] as? NSFont {
                let fontDescriptor = font.fontDescriptor.withSymbolicTraits([.bold])
                if let boldFont = NSFont.init(descriptor: fontDescriptor, size: font.pointSize) {
                    textView.textStorage?.setAttributes([NSAttributedString.Key.font : boldFont], range: textView.selectedRange)
                }
            }
}

然后这是我的下划线按钮的代码

@IBAction func underlineBTN(_ sender: Any) {
    if let fontt = textView.textStorage?.attributes(at: textView.selectedRange.location, longestEffectiveRange: nil, in: textView.selectedRange)[.font] as? NSFont {
                let fontDescriptorr = fontt.fontDescriptor.withSymbolicTraits([.bold])
                if NSFont.init(descriptor: fontDescriptorr, size: fontt.pointSize) != nil {
                    textView.textStorage?.setAttributes([NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue], range: textView.selectedRange)
                }
            }
       }

以下图片可为您提供帮助...

When I pressed the bold

然后当我按下下划线按钮时

When I press underline

xcode macos cocoa underline bold
1个回答
0
投票

使用addAttributes而不是setAttributes,它会覆盖选择中的先前属性。

© www.soinside.com 2019 - 2024. All rights reserved.