NSMutableAttributedString not working in tableviewcell with a specific range

时间:2017-05-16 09:33:37

标签: ios swift3 nsattributedstring ios10.3

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 

1 个答案:

答案 0 :(得分:4)

试试这个,

   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