iosswift3nsattributedstringios10.3

NSMutableAttributedString not working in tableviewcell with a specific range


I have followed this question but didn't solve my problem.

I have a tableview in ViewController , tableviewcell have a label. I want to set attributedString with NSStrikethroughStyleAttributeName. If i am setting complete string as a strikethrough it works but if i am setting as partial it doesn't works.

Below code for success result

let strOriginalPrice = "my price"
let strdiscountedPrice = "discounted price"
let strPrice = strOriginalPrice+" "+strdiscountedPrice

let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: strPrice)
 attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributeString.length))

cell.lblPrice.attributedText = attributeString 

Below code not working

let attributedDiscunt: NSMutableAttributedString =  NSMutableAttributedString(string: strPrice)
            attributedDiscunt.addAttribute(NSStrikethroughStyleAttributeName, value:2, range: NSMakeRange(0, strOriginalPrice.characters.count-1))

cell.lblPrice.attributedText = attributedDiscunt 

Solution

  • Try this,

       let strOriginalPrice = "my price"
        let strdiscountedPrice = "discounted price"
        let strPrice = strOriginalPrice+" "+strdiscountedPrice
    
     //        let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: strPrice)
    //        attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributeString.length))
    
        let attributedDiscunt: NSMutableAttributedString =  NSMutableAttributedString(string: strPrice)
        attributedDiscunt.addAttribute(NSStrikethroughStyleAttributeName, value:2, range: NSMakeRange(0, strOriginalPrice.characters.count-1))
        attributedDiscunt.addAttribute(NSBaselineOffsetAttributeName, value: 0, range: NSMakeRange(0, strOriginalPrice.characters.count-1))
    
    
        cell.lblPrice.attributedText = attributedDiscunt