iOS 11中使用Swift为NSAttributedString添加删除线失败求助
Hey there, let's dig into why your strikethrough isn't appearing on your NSAttributedString in iOS 11. I've run into similar quirks before, so here are the key checks and fixes to try:
Double-check your string type: If
theStringis anNSAttributedString(immutable), callingaddAttributes()won't modify it—this method only works onNSMutableAttributedString. Make sure you're initializing a mutable string first:let mutableString = NSMutableAttributedString(string: "Your target text")Verify the strikethrough style type: While
NSUnderlineStyle.styleSingle.rawValueis the right value, iOS 11 sometimes expects it wrapped in anNSNumberinstead of passing the rawUIntdirectly. Update your attribute dictionary to useNSNumber(value: ...):NSAttributedStringKey.strikethroughStyle: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue)Check color contrast: You're using
UIColor.whitefor the strikethrough color. If your text's foreground color is also white, the strikethrough will be invisible! Swap it for a contrasting color (likeUIColor.black) to test:NSAttributedStringKey.strikethroughColor: UIColor.blackValidate your range: Your current range is
NSMakeRange(0, 1), which only applies the strikethrough to the first character. If that character is a space, or your text is shorter than 1 character, you won't see anything. To apply it to the entire string, use:NSRange(location: 0, length: mutableString.length)Ensure your control uses
attributedText: If you're setting the string to aUILabelorUITextViewusing the regulartextproperty, all attributed styles will be ignored. Make sure you assign it toattributedTextinstead:yourLabel.attributedText = mutableString
Working Example Code
Putting it all together, here's a corrected snippet that should work in iOS 11:
// Create a mutable attributed string let mutableString = NSMutableAttributedString(string: "Sample Text with Strikethrough") // Define strikethrough attributes let strikethroughAttrs: [NSAttributedStringKey: Any] = [ .strikethroughStyle: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue), .strikethroughColor: UIColor.black, .foregroundColor: UIColor.white // Example text color (contrast with strikethrough) ] // Apply attributes to the entire string mutableString.addAttributes(strikethroughAttrs, range: NSRange(location: 0, length: mutableString.length)) // Assign to your label/text view yourLabel.attributedText = mutableString
内容的提问来源于stack exchange,提问作者eskimo

