【问题标题】:I want my text strike through extend on whitespace我希望我的文本在空白处通过扩展
【发布时间】:2017-05-14 10:52:46
【问题描述】:

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

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

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

【问题讨论】:

  • 请分享您目前尝试过的代码
  • 您不能直接这样做,因为这是本机行为!你可以像@Nirav D 在他的回答中建议的那样做一些技巧!

标签: ios nsattributedstring strikethrough


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    我还没有找到任何解决方案,但是使用您的最后一个选项意味着将第一个和最后一个字符添加为 . 和空格,您可以尝试一件事。将第一个和最后一个字符的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

    【讨论】:

      【解决方案3】:

      对于提出这个问题的人只想要一条穿过空白的水平线,这是这样做的方法(Swift 4):

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-04
        • 2021-12-11
        • 1970-01-01
        • 2016-01-13
        相关资源
        最近更新 更多