You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS 11中使用Swift为NSAttributedString添加删除线失败求助

Troubleshooting Strikethrough Not Showing in iOS 11 with Swift

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 theString is an NSAttributedString (immutable), calling addAttributes() won't modify it—this method only works on NSMutableAttributedString. Make sure you're initializing a mutable string first:

    let mutableString = NSMutableAttributedString(string: "Your target text")
    
  • Verify the strikethrough style type: While NSUnderlineStyle.styleSingle.rawValue is the right value, iOS 11 sometimes expects it wrapped in an NSNumber instead of passing the raw UInt directly. Update your attribute dictionary to use NSNumber(value: ...):

    NSAttributedStringKey.strikethroughStyle: NSNumber(value: NSUnderlineStyle.styleSingle.rawValue)
    
  • Check color contrast: You're using UIColor.white for the strikethrough color. If your text's foreground color is also white, the strikethrough will be invisible! Swap it for a contrasting color (like UIColor.black) to test:

    NSAttributedStringKey.strikethroughColor: UIColor.black
    
  • Validate 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 a UILabel or UITextView using the regular text property, all attributed styles will be ignored. Make sure you assign it to attributedText instead:

    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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:50:17