您可以使用 setBaseWritingDirection 选择器设置 UITextView 的书写方向:
UITextView *someTextView = [[UITextView] alloc] init];
[someTextView setBaseWritingDirection:UITextWritingDirectionLeftToRight forRange:[someTextView textRangeFromPosition:[someTextView beginningOfDocument] toPosition:[someTextView endOfDocument]]];
该代码有点棘手,因为 UITextView 支持文本的不同部分具有不同的书写方向。就我而言,我使用 [someTextView textRangeFromPosition:[someTextView beginOfDocument] toPosition:[someTextView endOfDocument]] 来选择 UITextView 的完整文本范围。如果您的需求不同,您可以调整该部分。
您可能还想检查 UITextView 中的文本是否是从 LTR 到 RTL。你可以这样做:
if ([someTextView baseWritingDirectionForPosition:[someTextView beginningOfDocument] inDirection:UITextStorageDirectionForward] == UITextWritingDirectionLeftToRight) {
// do something...
}
请注意,我使用 [someTextView beginOfDocument] 指定了文本的开头,并使用 UITextStorageDirectionForward 向前搜索。您的需求可能有所不同。
当然,如果您将 UITextView 子类化,请将所有这些代码示例替换为“self”而不是“someTextView”。
我建议阅读 UITextView 所遵循的 UITextInput 协议,网址为http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextInput Protocol/Reference/Reference.html http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextInput_Protocol/Reference/Reference.html.
关于在 iOS 5.1 或更早版本中使用 textAlignment 属性的警告:如果您将此方法与设置基本书写方向一起使用,则会遇到问题,因为在 UITextView 中向左对齐时的 RTL 文本实际上在视觉上向右对齐。将 RTL 书写方向的文本设置为右对齐会将其与 UITextView 的左侧对齐。