swift - 为什么我的 Playground 在 NSRange() 上崩溃

标签 swift nsattributedstring nsrange nsmutableattributedstring

我正在尝试了解 NSMutableAttributedStringNSAttributedString 所以我创建了一个简单的 Playground 来尝试一些事情。但是,即使在查看了很多有关 SO 的示例(例如其他地方的 hereNSRange from Swift Range?)之后,我仍然无法弄清楚一些问题。

问题出在长度属性上。如果我将长度指定为 attribLabelText.length,它会导致未捕获的异常。如果我指定 attribLabelText.length - 1 没有错误,但只有字母“Repor”具有我正在设置的属性:

enter image description here

import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {
    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white

        let label = getLabel1(labelText: "Report")
        view.addSubview(label)
        self.view = view
    }
}

func getLabel1(labelText: String) -> UILabel {
    let label = UILabel()
    label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
    label.textColor = .black

    let attribLabelText: NSMutableAttributedString = NSMutableAttributedString(string: labelText)
    let attributes = [
        NSAttributedString.Key.foregroundColor : UIColor.gray.cgColor,
        NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 14)
        ] as [NSAttributedString.Key : Any]

    attribLabelText.addAttributes(attributes, range: NSRange(location: 0, length: attribLabelText.length)) <-- this causes an uncaught exception of type NSException

    label.attributedText = attribLabelText

    return label
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()

我觉得这将是显而易见的事情,但我没有想法去尝试。谁能指出我做错了什么?

最佳答案

您应该为前景色传递 UIColor 而不是 CGColor

UILabel 在绘制字符串时似乎使用前景色属性略有不同,这取决于该属性是覆盖字符串的整个范围还是仅覆盖一个子范围。

当属性覆盖整个字符串时它使用的版本仅适用于 UIColor 但当属性仅覆盖子字符串时它使用的版本似乎也适用于 CGColor (虽然没有记录此行为,因此不应依赖它)这解释了为什么将 -1 添加到范围中可以避免异常。

关于swift - 为什么我的 Playground 在 NSRange() 上崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53285118/

相关文章:

ios - Websocket 在连接后立即断开连接

ios - NSAttributedString 2个字符串与新行的组合

ios - 将 "...Read More"添加到 UILabel 的末尾

ios - 初始化期间存储到 'currentRange' 的值永远不会被读取?

swift - SwiftUI 中的 firstIndex 是什么 - Swift

ios - CFNetwork 在 iOS 中使用 swift 崩溃

ios - UIImagePickerController 无法正确显示 GIF

ios - 如何从 NSAttributedString swift 中删除属性?

ios - 在Swift中使用NSRegularExpression在特定范围内为单词赋予属性

swift - 你如何设置范围: NSRangePointer in NSView knowsPageRange in Swift?