4

I am trying to set the textAlignment on the base of text direction if my textView has Text (Right to left like Arabic) direction then i want to set the textAlignment NSTextAlignmentRight else my alignment will be NSTextAlignmentLeft. Now the issue is i know how to check the text direction at the time of input in UITextView but once we get the text in UITextView then how we can check it. below is my screenshot and codeenter image description here

enter image description here

 if ([self.txtOutputTranslator baseWritingDirectionForPosition:[self.txtOutputTranslator beginningOfDocument] inDirection:UITextStorageDirectionForward] == UITextWritingDirectionLeftToRight)
{
    self.txtOutputTranslator.textAlignment=NSTextAlignmentLeft;
}
else
{
    self.txtOutputTranslator.textAlignment=NSTextAlignmentRight;

}

As my code show that i am checking the text Direction once i get the output text but it always running the else condition because i have set the UITextView alignment to Right in properties.any suggestion will be appreciated.Thanks in advance.

Soumya Ranjan
  • 4,817
  • 2
  • 26
  • 51
jamil
  • 2,419
  • 3
  • 37
  • 64
  • Are you open to suggestions? You could just center align all your text then you don't need to worry about whether text is left or right. – Zhang May 20 '14 at 07:18
  • Looking for best solution that will be last choice.BTW thanks for suggestion.:) – jamil May 20 '14 at 07:34

2 Answers2

3

it seems that the baseWritingDirectionForPosition method returns according to the textalignement of the textview.

Thus you need to check the writing direction depending on the language. And since you're doing the app manually you can check what is the language to be translated to, and you could have already specified which ones are rtl or ltr.

For further reading, you can look into A lighter way of discovering text writing direction and Detect Language of NSString

but your problem should be much easier. good luck

Community
  • 1
  • 1
TechSeeko
  • 1,521
  • 10
  • 19
3

@TechSeeko answer is right, here is Swift 4 example:

func textViewDidChange(_ textView: UITextView) {
    let baseWritingDirection = textView.baseWritingDirection(for: textView.beginningOfDocument, in: .forward)
    switch baseWritingDirection {
    case .leftToRight:
        textView.textAlignment = .left // for example
    case .rightToLeft:
        textView.textAlignment = .right // for example
    case .natural:
        // WARNING: use natural alignment carefully as it won't work with reusable table view cells. In common cases baseWritingDirection won't return this parameter
        textView.textAlignment = .natural
    }
}