The following code, will create a red color text, without strike-through.
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let text = "Hello World"
let textCount = text.count
let fullRange = NSRange(location: 0, length: textCount)
var attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(.foregroundColor, value: UIColor.green, range: fullRange)
attributedText.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: fullRange)
label.attributedText = attributedText
attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(.foregroundColor, value: UIColor.red, range: fullRange)
attributedText.removeAttribute(NSAttributedString.Key.strikethroughStyle, range: fullRange)
label.attributedText = attributedText
}
}
However, if I trigger label.text in between, it will cause the following strange behavior : A red color text, with strike-through created at the end of function.
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let text = "Hello World"
let textCount = text.count
let fullRange = NSRange(location: 0, length: textCount)
var attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(.foregroundColor, value: UIColor.green, range: fullRange)
attributedText.addAttribute(.strikethroughStyle, value: NSUnderlineStyle.single.rawValue, range: fullRange)
label.attributedText = attributedText
// Why this will cause a red color text, with strike-through created at the end of function?
label.text = text
attributedText = NSMutableAttributedString(string: text)
attributedText.addAttribute(.foregroundColor, value: UIColor.red, range: fullRange)
attributedText.removeAttribute(NSAttributedString.Key.strikethroughStyle, range: fullRange)
label.attributedText = attributedText
}
}
Does anyone what is the reason behind this behavior, and how I can avoid such? Thank you.