2011-02-05 13 views
13

mi idioma no es compatible con IOS por defecto, así Unicode no es una opción, así que estoy utilizando un tipo de letra verdadera incrustado en una UITextViewCambie la Dirección del texto UITextView

funciona en su mayor parte, sino mi problema es como el árabe, y el hebreo mi idioma está escrito de derecha a izquierda. Entonces necesito cambiar la dirección del texto (No alineación de texto).

hice algunas búsquedas, todos hablan de NSLocale y esas cosas, pero ¿se puede cambiar en el código? si puedo cambiarlo a algo como árabe/hebreo funcionaría, supongo, pero debería hacerse en código, porque no quiero cambiar el idioma del teléfono.

¿Cuáles son mis opciones de entrada de texto? Cualquier ayuda sería apreciada.

Gracias.

+0

También quiero implementar la misma funcionalidad que la suya. Quiero implementar ** Teclado Urdu ** con la dirección del texto de ** De derecha a izquierda **. Entonces, ¿encontró alguna manera de obtener caracteres de teclado personalizados con dirección de texto RTL (como mencionó en su comentario en la respuesta aceptada)? Si es ** Sí **, por favor comparta el código aquí. También estoy atrapado en una situación como la tuya. Por favor ayuda. – Bhavin

+0

[Siga este enlace para obtener una solución a este problema en SWIFT] (http://stackoverflow.com/questions/4905500/change-the-uitextview-text-direction/41424462#41424462) –

Respuesta

7

Tu pregunta realmente me ha interesado. Entonces, en cuestión de horas, se me ocurrió una solución. Está lejos de ser perfecto, pero puedes usarlo y arreglar los errores restantes. Este es un controlador de vista simple con vista de texto. Se puede añadir texto escribiéndola o puede establecer el valor con

-(void) setText:(NSString*) txt; 

Así que aquí está el código:

ReverseTextVC.h

@interface ReverseTextVC : UIViewController <UITextViewDelegate> { 
    NSMutableArray* _lines; 
    UITextView* _tv; 
} 

/** 
Returns reversed text. 
The lines is also updated. This array contains all lines. You should pass this array again if you want to append the text. 
*/ 
+(NSString*) reverseText:(NSString*) text withFont:(UIFont*) font carretPosition:(NSRange*) cpos Lines:(NSMutableArray*) lines Bounds:(CGRect) bounds; 

-(void) setText:(NSString*) txt; 

@end 

ReverseTextVC.m

@implementation ReverseTextVC 

-(id) init { 
    if(self = [super init]) { 
     _tv = [[UITextView alloc] initWithFrame: CGRectMake(0, 0, 320, 480)]; 
     _tv.textAlignment = UITextAlignmentRight; 
     _tv.delegate = self; 
     [self.view addSubview: _tv]; 
     [_tv release]; 

     _lines = [[NSMutableArray alloc] initWithCapacity: 10]; 
     [_lines addObject: [NSMutableString stringWithCapacity: 255]]; 
    } 

    return self; 
} 

-(void) dealloc { 
    [_lines release]; 

    [super dealloc]; 
} 

-(void) loadView { 
    UIView* v = [[UIView alloc] initWithFrame: CGRectMake(0, 20, 320, 480)]; 
    self.view = v; 
    [v release]; 
} 

-(void) setText:(NSString*) txt { 
    NSString* result = nil; 
    NSRange rng; 
    NSArray* words = [txt componentsSeparatedByString: @" "]; 
    //we should do it iteratively (cause it's the simplest way =)) 
    for(NSString* word in words) { 
     word = [NSString stringWithFormat: @"%@ ", word]; 
     for(int i=0; i<[word length]; ++i) { 
      NSRange r; r.length = 1; r.location = i; 
      result = [ReverseTextVC reverseText: [word substringWithRange: r] 
                   withFont: _tv.font 
                 carretPosition: &rng 
                   Lines: _lines 
                   Bounds: _tv.bounds]; 
     } 
    } 

    _tv.text = result; 
} 


#pragma mark - 
#pragma mark UITextViewDelegate 

-(BOOL) textView:(UITextView*) textView shouldChangeTextInRange:(NSRange) range replacementText:(NSString*) text { 
    NSRange rng; 

    textView.text = [ReverseTextVC reverseText: text 
             withFont: textView.font 
           carretPosition: &rng 
             Lines: _lines 
             Bounds: textView.bounds]; 

    textView.selectedRange = rng; 

    return NO; 
} 


#pragma mark - 
#pragma mark Static 

+(NSString*) reverseText:(NSString*) text withFont:(UIFont*) font carretPosition:(NSRange*) cpos Lines:(NSMutableArray*) lines Bounds:(CGRect) bounds { 
    cpos->length = 0; 
    cpos->location = 0; 
    if([text length]) { 
     if(![text isEqualToString: @"\n"]) { 
      [(NSMutableString*)[lines lastObject] insertString: text 
                 atIndex: 0]; 
     } else { 
      [lines addObject: [NSMutableString stringWithCapacity: 255]]; 
     } 
    } else { 
     //backspace 
     //TODO: 
     NSRange del_rng; 
     del_rng.length = 1; 
     del_rng.location = 0; 
     if([(NSMutableString*)[lines lastObject] length]) { 
      [(NSMutableString*)[lines lastObject] deleteCharactersInRange: del_rng]; 
     } 
     if(![(NSMutableString*)[lines lastObject] length]) { 
      [lines removeLastObject]; 
     } 
    } 

    CGSize sz = [(NSString*)[lines lastObject] sizeWithFont: font]; 
    if(sz.width >= bounds.size.width-15) { 
     NSMutableArray* words = [NSMutableArray arrayWithArray: [(NSString*)[lines lastObject] componentsSeparatedByString: @" "]]; 
     NSString* first_word = [words objectAtIndex: 0]; 
     [words removeObjectAtIndex: 0]; 
     [(NSMutableString*)[lines lastObject] setString: [words componentsJoinedByString: @" "]]; 
     [lines addObject: [NSMutableString stringWithString: first_word]]; 
    } 

    NSMutableString* txt = [NSMutableString stringWithCapacity: 100]; 
    for(int i=0; i<[lines count]; ++i) { 
     NSString* line = [lines objectAtIndex: i]; 
     if(i<([lines count]-1)) { 
      [txt appendFormat: @"%@\n", line]; 
      cpos->location += [line length]+1; 
     } else { 
      [txt appendFormat: @"%@", line]; 
     } 
    } 

    return txt; 
} 

@end 

Espero que te ayude =)

+1

Realmente me alegro de esto =) – Max

+0

Realmente útil, traté de usarlo con este teclado personalizado: https://github.com/kulpreetchilana/Custom-iOS-Keyboards pero obtengo la dirección devuelta a la configuración predeterminada. ¿Podría ayudarnos cómo integrar su código con este control de teclado personalizado o cualquier sugerencia similar? Solo queremos obtener caracteres de teclado personalizados con dirección de texto RTL. Gracias. – hafedh

+0

alguna idea por favor @Max? – hafedh

-3

El Iphone no puede mostrar el hebreo y otros textos de derecha a izquierda correctamente. entonces pienso que no hay forma de que puedas cambiar la dirección del texto.

+0

No he tenido problemas para mostrar texto árabe antes, y supongo que es el mismo para hebreo, aunque no puedo hablar en cuanto a la entrada de texto. –

0

Hola Creo que al usar UIWebView con html y css puede hacer el trabajo

+0

UIWebView se usa solo para mostrar contenido. –

9

Puede colocar un carácter Unicode "incrustación de derecha a izquierda" al inicio de cada línea en la vista de texto.

Nombre: DERECHA A IZQUIERDA EMBEDDING Unicode: 202B UTF8: E2 80 AB

Tenga en cuenta que este personaje es invisible (No hay formas).

El siguiente fragmento de código reemplaza los caracteres de fin de línea con una cadena EOL + RTL_EMBEDDING:

appDescription.text = [rtlDescriptionString stringByReplacingOccurrencesOfString:@"\n" withString:@"\n‫;[" 
4

sólo tiene que utilizar el carácter Unicode 202B para DERECHA A IZQUIERDA incrustación.

Ejemplo:

uiTextView.text = [NSString stringWithFormat: @ "\ u202B% @", textString];

0

Para mí, simplemente agregar \ u202B en la cadena directamente en el archivo .strings no funcionó (el resultado final se imprimirá, literalmente, imprimirá la parte "202B"). Sin embargo, agregar \ u202B a la cadena después de que regrese de la llamada a localizedStringForKey es suficiente.

Así que mi solución, inserté la cadena arbitraria "RLE_SYMBOL" directamente en la cadena en el archivo .strings, luego de la llamada a localizedStringForKey reemplazo "RLE_SYMBOL" por "\ u202B".

Un poco indirecta, no es la mejor solución pero es una solución rápida.

mystring = [mystring stringByReplacingOccurrencesOfString:@"RLE_SYMBOL" withString:@"\u202B"]; 
0

He estado enfrentando el mismo problema. Mi lenguaje es similar al árabe, escribiendo de derecha a izquierda. La solución más simple para mí fue cambiar la alineación del texto a la derecha y mover el cursor hacia la izquierda después de ingresar cada carácter. Esto funciona en SWIFT 3.0

func textViewDidChange(_ textView: UITextView) { 

    let newPosition = myTextView.beginningOfDocument 
    myTextView.selectedTextRange = myTextView.textRange(from: newPosition, to: newPosition) 

    print(myTextView.text) 


    return 

} 
Cuestiones relacionadas