我希望我的文本在空白处延伸

I want my text strike through extend on whitespace

我使用 NSAttributeString 在我的文本上设置删除线,我希望它在 whitespace 上延伸。

我已经设置了正确的范围,但是删除线只覆盖了文本字符。删除线是忽略空白,除非我在它前后添加一些非空文本。

如何在没有额外文本的情况下使删除线在空白处延伸?

我还没有找到任何解决方案,但您的最后一个选项意味着将第一个和最后一个字符添加为 . 和 space 您可以尝试一件事。将第一个和最后一个字符的 NSForegroundColorAttributeName 设置为标签的背景颜色,或者将 NSFontAttributeName 设置为 UIFont.systemFont(ofSize: 0.1)。所以它会是这样的。您没有指定您的回答语言,所以我在最新的 Swift 3.

中发布答案
let attributedText = NSMutableAttributedString(string: self.lbl.text!)
attributedText.addAttributes([NSStrikethroughStyleAttributeName: 2], range: NSMakeRange(0, self.lbl.text!.characters.count))
self.lbl.attributedText = attributedText

使用前 NSForegroundColorAttributeName & NSFontAttributeName

现在您可以使用 NSForegroundColorAttributeNameNSFontAttributeName 来隐藏第一个和最后一个 dot(.) 个字符。

let attributedText = NSMutableAttributedString(string: self.lbl.text!)
attributedText.addAttributes([NSStrikethroughStyleAttributeName: 2], range: NSMakeRange(0, self.lbl.text!.characters.count))
attributedText.addAttributes([NSForegroundColorAttributeName: UIColor.white], range: NSMakeRange(0, 1))
attributedText.addAttributes([NSForegroundColorAttributeName: UIColor.white], range: NSMakeRange(self.lbl.text!.characters.count - 1, 1))
//Or either Set NSFontAttributeName instead of NSForegroundColorAttributeName
//attributedText.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 0.1)], range: NSMakeRange(0, 1))
//attributedText.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 0.1)], range: NSMakeRange(self.lbl.text!.characters.count - 1, 1))
self.lbl.attributedText = attributedText

使用NSForegroundColorAttributeNameNSFontAttributeName

对于只希望通过空格的水平线来回答这个问题的人,这是这样做的方法 (Swift 4):

let line = String(repeating: "\u{23AF}", count: 10)

我今天遇到了同样的问题,现有的答案都没有给我一个我认为应该是直截了当的解决方案。经过一番研究,我找到了一个使用Unicode字符的更简洁的解决方案。

用一个或多个不间断的 Unicode space 字符填充文本的每一侧 (U+00A0) 根据需要扩展行:

let attributedText = NSAttributedString(
    string: "\u{00A0}\(someText)\u{00A0}",
    attributes: [.strikethroughStyle: NSUnderlineStyle.single.rawValue]
)