Ios 我希望我的文本在空白处划过扩展

Ios 我希望我的文本在空白处划过扩展,ios,nsattributedstring,strikethrough,Ios,Nsattributedstring,Strikethrough,我使用NSAttributeString在我的文本上设置strike-through,我希望它扩展到whitespace 我已经设置了正确的范围,但是删除只覆盖文本字符。除非我在空格前后添加一些非空文本,否则删除是忽略空格 如何在没有额外文本的情况下通过扩展空白来进行删除 我还没有找到任何解决方案,但使用最后一个选项意味着将第一个和最后一个字符添加为,您可以尝试一件事。将第一个和最后一个字符的NSForegroundColorAttributeName设置为标签的背景色,或使用UIFont.sy

我使用
NSAttributeString
在我的文本上设置strike-through,我希望它扩展到
whitespace

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

如何在没有额外文本的情况下通过扩展空白来进行删除


我还没有找到任何解决方案,但使用最后一个选项意味着将第一个和最后一个字符添加为
,您可以尝试一件事。将第一个和最后一个字符的
NSForegroundColorAttributeName
设置为标签的背景色,或使用
UIFont.systemFont(ofSize:0.1)
设置
NSFontAttributeName
。所以事情会是这样的。您还没有指定您的答案语言,所以我将在最新的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

现在,您可以使用
NSForegroundColorAttributeName
NSFontAttributeName
隐藏第一个和最后一个
点(.)
字符

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
使用
NSForegroundColorAttributeName
NSFontAttributeName

对于回答这个问题的人来说,他们只想在空白处画一条横线,这是一种方法(Swift 4):


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

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

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

请共享您尝试的代码,因为这是本机行为,您无法直接执行!你可以像@Nirav D在他的回答中建议的那样做一些把戏!
let attributedText = NSAttributedString(
    string: "\u{00A0}\(someText)\u{00A0}",
    attributes: [.strikethroughStyle: NSUnderlineStyle.single.rawValue]
)