swiftwatchkitnsattributedstringwkinterfacetable

WKInterfaceLabel Attributed String Fails on Width


I am using an attributed string to strikethrough text in a WKInterfaceLabel. This works up until the point where the text is longer than the width of the watch and therefore you see ... Actually the same thing happens on iOS; however, you can clip content which resolves the issue. On the watch, clipping is not available.

How can I strikethrough the visible text when the overall width is beyond the screen's bounds? Below is the code:

let attributedString = NSMutableAttributedString(string: self.fileTextArray[i])
attributedString.addAttribute(NSStrikethroughStyleAttributeName, value: NSNumber(value: NSUnderlineStyle.styleThick.rawValue), range: NSMakeRange(0, attributedString.length))
attributedString.addAttribute(NSStrikethroughColorAttributeName, value: UIColor.red, range: NSMakeRange(0, attributedString.length))

row.translatedTextLabel.setAttributedText(attributedString)

Solution

  • This appears to be a bug but one with a workaround. The fix is to use the following line of code:

    attributedString.addAttribute(NSBaselineOffsetAttributeName, value: 0, range: NSMakeRange(0, attributedString.length))
    

    This solves it in both Watch OS as well as iOS.

    Additional detail here: iOS 10.3: NSStrikethroughStyleAttributeName is not rendered if applied to a sub range of NSMutableAttributedString