Home > Blockchain >  How to reset or reverse a String after its been attributed
How to reset or reverse a String after its been attributed

Time:11-26

I have a TableView and in each cell, I have a UISwitch which if enabled, modifies the label in the row.

Here is how I am modifying it:

@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
        
    }
}

I am running into an issue to reset the label back to the original string. I will do a demo right now. I have added several print statements to help with debugging. We can see that initialLabel holds the correct cell value, but for some reason doesn't assign it.

Here is the demo:

enter image description here


Why is it not displaying my taskLabel with the right string?

CodePudding user response:

you need to remove the strikethrough in off state

Removes the named attribute from the characters in the specified range. Ref removeAttribute:range:

 @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
}
  • Related