UItextView arabic text aligned to right

Khalil Ghaus picture Khalil Ghaus · Mar 26, 2012 · Viewed 9.9k times · Source

Using my custom arabic keyboard on UItextView inputView, I m filling my textView with the arabic text but cannot get the written text align to right....Need help to align text to right.

-(BOOL)textViewShouldBeginEditing:(UITextView *)textView{

 if(showCustomKeyboard==NO){
 [textView resignFirstResponder];
 textView.inputView=nil;
 [textView becomeFirstResponder];
 return YES; 
}

 else{
     [textView resignFirstResponder];
     if(customKeyboard==nil){
     customKeyboard=[[CustomKeyboard alloc] initWithFrame:CGRectMake(0, 264, 320, 216)];
     [customKeyboard setDelegate:self];
 } 
 if([[UIApplication sharedApplication] respondsToSelector:@selector(inputView)]){
     if (textView.inputView == nil) {
           textView.inputView = customKeyboard;
           [textView becomeFirstResponder];
     }
 } 
    self.customKeyboard.currentField=textView;
    [textView becomeFirstResponder];
 }
 return YES; 
}

Answer

Anton picture Anton · Jun 2, 2012

You can set the writing direction of a UITextView using the setBaseWritingDirection selector:

UITextView *someTextView = [[UITextView] alloc] init];
[someTextView setBaseWritingDirection:UITextWritingDirectionLeftToRight forRange:[someTextView textRangeFromPosition:[someTextView beginningOfDocument] toPosition:[someTextView endOfDocument]]];

The code is a little tricky because UITextView supports having different parts of the text with different writing directions. In my case, I used [someTextView textRangeFromPosition:[someTextView beginningOfDocument] toPosition:[someTextView endOfDocument]] to select the full text range of the UITextView. You can adjust that part if your needs are different.

You may also want to check whether the text in your UITextView is LTR to RTL. You can do that with this:

if ([someTextView baseWritingDirectionForPosition:[someTextView beginningOfDocument] inDirection:UITextStorageDirectionForward] == UITextWritingDirectionLeftToRight) {
    // do something...
}

Note that I specified the start of the text using [someTextView beginningOfDocument] and searched forward using UITextStorageDirectionForward. Your needs might differ.

If you subclass UITextView replace all these code samples with "self" and not "someTextView", of course.

I recommend reading about the UITextInput protocol, to which UITextView conforms, at http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextInput_Protocol/Reference/Reference.html.

Warning about using the textAlignment property in iOS 5.1 or earlier: if you use it with this approach together with setting the base writing direction, you will have issues because RTL text when aligned left in a UITextView actually aligns to the right visually. Setting text with an RTL writing direction to align right will align it to the left of the UITextView.