Reputation: 656
I use NSAttributeString
to set strike through on my text, I want it extend on whitespace
.
I already set the correct range, but the strike through only cover the text characters. The strike through is ignore the whitespace unless I add some non-empty text before and after it.
How can I make the strike through extend on whitespace without extra text?
Upvotes: 4
Views: 1517
Reputation: 2372
I have come across the same problem today, and neither existing answers gave me a solution I felt was as straightforward as it should be. After some research, I found a more concise solution using Unicode characters.
Padding each side of your text with one or more non-breaking Unicode space characters (U+00A0)
extends the line as desired:
let attributedText = NSAttributedString(
string: "\u{00A0}\(someText)\u{00A0}",
attributes: [.strikethroughStyle: NSUnderlineStyle.single.rawValue]
)
Upvotes: 3
Reputation: 4097
For people coming to this question who only want a horizontal line through whitespace, this is the way to do it (Swift 4):
let line = String(repeating: "\u{23AF}", count: 10)
Upvotes: 1
Reputation: 72410
I haven't found any solution but with your last option means adding first and last character as .
with space you can try one thing. Either set the NSForegroundColorAttributeName
of that first and last character to your background color of label or set the NSFontAttributeName
with UIFont.systemFont(ofSize: 0.1)
. So it will be goes like this. You haven't specify your answer language so i'm posting answer in latest 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
Before using NSForegroundColorAttributeName
& NSFontAttributeName
Now you can use either NSForegroundColorAttributeName
or NSFontAttributeName
to hide first and last dot(.)
character.
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
After using NSForegroundColorAttributeName
or NSFontAttributeName
Upvotes: 2