且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

不可编辑的 UITextView 左对齐 RTL(阿拉伯语、希伯来语等)文本

更新时间:2023-02-26 12:39:19

解决了!结果很简单:只需将 textAlignment 设置为 UITextAlignmentRight.

Solved it! Turns out it's very simple: just set the textAlignment to UITextAlignmentRight.

UITextView 在可编辑和不可编辑时的工作方式不同,尤其是在涉及 RTL 文本时.如果基本书写方向是可编辑文本视图中的 RTL,则必须将文本左对齐,而不是右对齐,以便文本真正右对齐(RTL 书写方向翻转了默认值!)

UITextView works differently when editable and not, especially when it comes to RTL text. If the base writing direction is RTL in an editable text view, you must align the text left, not right, in order for the text to actually align right (the RTL writing direction flips the defaults!)

所以,当你有一个 UITextView 时,你可能要先检查 editable 属性,然后使用第一个字符的书写方向(这是 iOS 确定文本是左对齐还是右对齐)来设置 textAlignment 属性.

So, when you have a UITextView, you may want to first check the editable property and then use the writing direction of the first character (this is how iOS determines whether the text is aligned left or right) to set the textAlignment property.

例如:

// check if the text view is both not editable and has an RTL writing direction
if (!someTextView.editable && [someTextView baseWritingDirectionForPosition:[someTextView beginningOfDocument] inDirection:UITextStorageDirectionForward] == UITextWritingDirectionRightToLeft) {
        // if yes, set text alignment right
        someTextView.textAlignment = UITextAlignmentRight;
    } else {
        // for all other cases, set text alignment left
        someTextView.textAlignment = UITextAlignmentLeft;
    }
}

iOS 6 更新:

在 iOS 6 中,UITextView 的 textAlignment 属性实际上对应于它在屏幕上的外观.对于 iOS 6,只需将 textAlignment 设置为您想要查看的方向.上述代码的工作原理与 iOS 5.1 及更早版本的描述相同.

In iOS 6, a UITextView's textAlignment property actually corresponds to its appearance on the screen. For iOS 6, just set the textAlignment to the direction you want to see it. The above code works as described for iOS 5.1 and earlier.

我希望这可以帮助其他人处理这个问题!

I hope this helps anyone else dealing with this issue!