2017-05-16 3 views
2

J'ai suivi this question mais n'a pas résolu mon problème. J'ai un tableview dans ViewController, tableviewcell J'ai une étiquette. Je veux définir attributedString avec NSStrikethroughStyleAttributeName. Si je mets une chaîne complète en tant que barré, cela fonctionne mais si je règle comme partielle cela ne fonctionne pas.NSMutableAttributedString ne fonctionne pas dans tableviewcell avec une plage spécifique

Ci-dessous le code pour résultat de succès

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 

Ci-dessous le code ne fonctionne pas

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

cell.lblPrice.attributedText = attributedDiscunt 
+1

iOS 10.3? Si c'est le cas: http://stackoverflow.com/questions/43074652/ios-10-3-nsstrikethroughstyleattributename-is-not-rendered-if-applied-to-a-sub/43359207 – Larme

+0

Yep, c'est un bug dans iOS 10.3. Les attributs ne fonctionnent plus pour une plage de votre chaîne, seulement pour toute la chaîne. – Koen

+0

La copie possible de [iOS 10.3: NSStrikethroughStyleAttributeName n'est pas rendue si elle est appliquée à une sous-plage de NSMutableAttributedString] (http://stackoverflow.com/questions/43074652/ios-10-3-nsstrikethroughstyleattributename-is-not-rendered-if- appliqué-à-un-sub) – Larme

Répondre

4

Essayez ceci,

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