Search code examples
iosobjective-cplaceholderdirection

placeholder is not taking NSTextAlignmentNatural


I have an app where I have UITextField.

My app is English - Arabic app.

Now what I have is as below.

addPostVideoURL.backgroundColor = [UIColor clearColor];
addPostVideoURL.textAlignment = NSTextAlignmentNatural; <-- Setting alignment
addPostVideoURL.textColor = pGray_343434;
addPostVideoURL.placeholder = localize(@"videoURL");
[addPostVideoURL setValue:pGray_343434 forKeyPath:@"_placeholderLabel.textColor"];
addPostVideoURL.font = [self adjustDefaultFont:40];
addPostVideoURL.autocorrectionType = UITextAutocorrectionTypeNo;

If you see, I have set the Alignment text as NSTextAlignmentNatural. I did this because if keyboard is arabic (& my app is english or arabic), I want textfield to start from right side.

With this when I changed the keyboard to English, text field start from LTR & if I change keyboard to arabic, textfield start from RTL. However, the placeholder that I have is always at the left.

Any way how can I make placeholder alignment based on the app language?


Solution

  • To tackle this issue, below is what I did...

    1. In .pch I add below

      #define myDirection001 ([localize(@"myLang") isEqualToString:@"en"]) ? NSTextAlignmentLeft : NSTextAlignmentRight

    2. Then have code like below.

      addPostVideoURL.backgroundColor = [UIColor clearColor];
      addPostVideoURL.textAlignment = myDirection001;
      addPostVideoURL.textColor = pGray_343434;
      addPostVideoURL.placeholder = localize(@"videoURL");
      [addPostVideoURL setValue:pGray_343434 forKeyPath:@"_placeholderLabel.textColor"];
      addPostVideoURL.font = [self adjustDefaultFont:40];
      addPostVideoURL.autocorrectionType = UITextAutocorrectionTypeNo;
      

    Make sure that delegate is set as we are going to call delegates now.

    1. Call delegate methods.

      - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
          textField.textAlignment = NSTextAlignmentNatural;    
          return YES;
      }
      
      - (BOOL)textFieldShouldReturn:(UITextField *)textField{
          textField.textAlignment = (textField.text.length==0) ? myDirection001 : NSTextAlignmentNatural;
          return YES;
      }