iOS 10.3:如果应用于NSMutableAttributedString的子范围,则不呈现NSStrikethroughStyleAttributeName

rsh*_*hev 46 uikit ios swift

NSMutableAttributedString如果应用范围不是整个字符串范围,则不会呈现作为属性添加到实例的删除线(单,双,...).

出现这种情况使用addAttribute(_ name: String, value: Any, range: NSRange), insert(_ attrString: NSAttributedString, at loc: Int),append(_ attrString: NSAttributedString),...

在早期iOS 10.3测试版中被Apple打破,并未在10.3决赛中修复.

信用:https: //openradar.appspot.com/31034683

tom*_*nas 88

设置基线偏移量似乎可以解决它:

[attributedStr addAttribute:NSBaselineOffsetAttributeName value:@0 range:NSMakeRange(0, 10)];
[attributedStr addAttribute:NSStrikethroughStyleAttributeName value:@2 range:NSMakeRange(0, 10)];
Run Code Online (Sandbox Code Playgroud)

这是iOS 10.3中的已知错误


Mug*_*nth 24

添加NSBaselineOffsetAttributeName,如解释在这里,在属性串带回删除线.覆盖drawText:in:可能很慢,尤其是在Collection View或Table View Cells上.


rsh*_*hev 14

为我们的特定场景找到了一种解决方法(我们没有使用UILabel的属性指定任何样式,但所有样式都具有NSAttributedString属性):

/// This UILabel subclass accomodates conditional fix for NSAttributedString rendering broken by Apple in iOS 10.3
final class PriceLabel: UILabel {

    override func drawText(in rect: CGRect) {
        guard let attributedText = attributedText else {
            super.drawText(in: rect)
            return
        }

        if #available(iOS 10.3, *) {
            attributedText.draw(in: rect)
        } else {
            super.drawText(in: rect)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:如果您将UILabel的样式属性与NSAttributedString属性混合,您应该考虑在渲染之前创建新的属性字符串,在其上应用UILabel的样式,然后在其上重新应用所有attributedText属性.


小智 10

swift 3工作代码用10.3测试

let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: "?3500")
attributeString.addAttribute(NSBaselineOffsetAttributeName, value: 0, range: NSMakeRange(0, attributeString.length))
attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 1, range: NSMakeRange(0, attributeString.length))
productPriceLabel.attributedText = attributeString
Run Code Online (Sandbox Code Playgroud)


Yuc*_*ong 10

斯威夫特4

let text = "Hello World"
let textRange = NSMakeRange(0, text.count)
let attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(NSAttributedStringKey.strikethroughStyle,
                            value: NSUnderlineStyle.styleSingle.rawValue,
                            range: textRange)
myLabel.attributedText = attributedText
Run Code Online (Sandbox Code Playgroud)

  • 关键是使用```NSUnderlineStyle.styleSingle.rawValue````````` NSUnderlineStyle.styleSingle```. (5认同)