Swift中NSWritingDirection导致NSAttributedString崩溃问题求助
Hey there, let's break down why your code is crashing and fix it right away!
崩溃根源
The crash happens because of a type mismatch when setting the writingDirection attribute. The NSAttributedStringKey.writingDirection expects an array of integers ([Int]), but you're passing a single integer value directly.
When you combine NSWritingDirection.rightToLeft.rawValue and NSWritingDirectionFormatType.override.rawValue with a bitwise OR, you get a single Int—but the attribute requires this value to be wrapped in an array. This type mismatch triggers an unrecognized selector or type error, leading to the crash.
修正后的代码
Here's the fixed version of your code, with the writingDirection value properly wrapped in an array:
let myString = "Swift Attributed String" let myAttribute = [ NSAttributedStringKey.foregroundColor: UIColor.blue, // Wrap the combined raw value in an array NSAttributedStringKey.writingDirection: [NSWritingDirection.rightToLeft.rawValue | NSWritingDirectionFormatType.override.rawValue] ] as [NSAttributedStringKey : Any] let myAttrString = NSAttributedString(string: myString, attributes: myAttribute) // Set the attributed text on your label self.labelUsername.attributedText = myAttrString
额外说明
The writingDirection attribute uses an array because it supports handling mixed-direction text (e.g., a string with both left-to-right and right-to-left content). Even if you only need one direction rule, you must wrap the raw value in an array to match the expected type.
内容的提问来源于stack exchange,提问作者Abdullah Umer

