我有一個TableViewand 在每個單元格中,UISwitch如果啟用,我有一個修改行中的標簽。
這是我修改它的方式:
@IBAction func completedTask(_ sender: UISwitch) {
//Getting original taskLabel
let initalLabel = taskLabel.text
//Modifying the string to have a line through it. Storing it in variable attributeString
let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: taskLabel.text!)
attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))
if sender.isOn{
print("attributed Label --> ",attributeString)
taskLabel.textColor = UIColor.red
taskLabel.attributedText = attributeString
}else{
print("initial Label --> ",initalLabel!)
taskLabel.text = initalLabel
taskLabel.textColor = UIColor.black
}
}
我遇到了將標簽重置回原始字串的問題。我馬上做一個演示。我添加了幾個列印陳述句來幫助除錯。我們可以看到 initialLabel 保存了正確的單元格值,但由于某種原因沒有分配它。
這是演示:

為什么它沒有用正確的字串顯示我的 taskLabel?
uj5u.com熱心網友回復:
您需要在關閉狀態下洗掉洗掉線
從指定范圍內的字符中洗掉命名屬性。參考removeAttribute:范圍:
@IBAction func completedTask(_ sender: UISwitch) {
//Modifying the string to have a line through it. Storing it in variable attributeString
let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: taskLabel.text!)
if sender.isOn{
attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))
}else{
attributeString.removeAttribute(NSAttributedStringKey.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))
}
taskLabel.textColor = sender.isOn ? .red : .black
taskLabel.attributedText = attributeString
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/367364.html
