ios - NSAttributedString 背景色渲染 iOS 10 VS iOS 11

标签 ios swift nsattributedstring

我正在尝试使用 NSAttributedString 原生渲染“突出​​显示”,我注意到它在 iOS 10 上非常漂亮,但在 iOS 11 上非常无聊。 我可以说 iOS 10 渲染是正确的。

iOS 10:

enter image description here

iOS 11 是完全错误的,但我猜他们出于性能原因决定牺牲一些绘图计算。

iOS 11:

enter image description here

我尝试了各种设置,但似乎不可能“轻松”实现,即不编写任何自定义字符串绘制代码,即可在 iOS 11 上实现 iOS 10 渲染。

最佳答案

所以,我终于找到了一个可靠的解决方案,而且实际上很简单。您需要有一个 LayoutManager,因此最好使用 UITextView 或您自己的自定义文本抽屉。这是我的自定义 UITextView 子类:

class QuoteTextView: UITextView, NSLayoutManagerDelegate {

    var highlightColor = UIColor.gl_defaultHighlight

    override var text: String! {
        didSet {
            setNeedsDisplay()
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        let padding = textContainer.lineFragmentPadding
        textContainerInset = UIEdgeInsets(top: 0, left: -padding, bottom: 0, right: -padding)
        layoutManager.delegate = self
    }

    override func draw(_ rect: CGRect) {
        super.draw(rect)

        layoutManager.enumerateLineFragments(forGlyphRange: NSMakeRange(0, text.utf16.count)) { (rect1, lineRect, container, range, _) in
            let path = UIBezierPath(rect: CGRect(x: lineRect.origin.x,
                                                 y: lineRect.origin.y - 2,
                                                 width: lineRect.size.width,
                                                 height: lineRect.size.height - 4))
            self.highlightColor.setFill()
            path.fill()
        }
    }

    func layoutManager(_ layoutManager: NSLayoutManager,
                       lineSpacingAfterGlyphAt glyphIndex: Int,
                       withProposedLineFragmentRect rect: CGRect) -> CGFloat {
        return 5
    }

    func layoutManager(_ layoutManager: NSLayoutManager,
                       shouldUse action: NSLayoutManager.ControlCharacterAction,
                       forControlCharacterAt charIndex: Int) -> NSLayoutManager.ControlCharacterAction {
        return .lineBreak
    }
}

关于ios - NSAttributedString 背景色渲染 iOS 10 VS iOS 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50912854/

相关文章:

swift - 在 APPNAME UITests-Runner.app 的捆绑 NSBundle 中找不到名为 'Main' 的 Storyboard

swift - 旋转设备时切换到另一个 View Controller

HTML 格式无法快速与 UILabel 一起使用

iphone - 在 iOS 6 中使用格式输入 UITextView

ios - SwiftUI 状态变量未更新

ios - Pod init 或 pod update 出现以下错误

ios - UICollectionView 垂直分隔符

ios - 使用旧金山字体将 HTML 解析为 NSAttributedString? (iOS 9)

ios - 设备锁定时使用 AVAudioSessionCategoryAmbient 播放音频

ios - 构建应用程序时找不到 Cocoapods header