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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:56:53