简体   繁体   English

修剪NSMutableAttributedString中的第一个字符

[英]Trim first character in NSMutableAttributedString

I am using NSMutableAttributedString to show attributed string in label. 我正在使用NSMutableAttributedString在标签中显示属性字符串。 Is there way to trim first character of NSMutableAttributedString without change in attributes. 是否可以在不更改属性的情况下修剪NSMutableAttributedString的第一个字符。

No because one of the attributes of the attributes is the range of the string they effect, and those will become invalid if the string length changes. 否,因为属性的一个属性是它们影响的字符串的范围,并且如果字符串长度更改,这些属性将无效。

The best approach would be to reconstruct the attributed string from scratch, which might be simple or difficult, depending on whether you know the attributes to add. 最好的方法是从头开始重建属性字符串,这可能很简单也很困难,具体取决于您是否知道要添加的属性。

NSMutableAttributedString supports the deleteCharacters(in:NSRange) method: NSMutableAttributedString支持deleteCharacters(in:NSRange)方法:

@IBOutlet weak var topLabel: NSTextField!
@IBOutlet weak var bottomLabel: NSTextField!
...
    let textAttributes : [String : Any] = [
        NSForegroundColorAttributeName : NSColor.blue,
        NSFontAttributeName : NSFont(name: "Menlo", size: 12.0)!
    ]
    let text = NSMutableAttributedString(string: "ABCDEF",
                                         attributes: textAttributes)
    topLabel.attributedStringValue = text
    text.deleteCharacters(in: NSMakeRange(0,1))
    bottomLabel.attributedStringValue = text
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM