Chenya Zhang Chenya Zhang - 10 months ago 58
iOS Question

iOS Localization Best Practice for UILabel + UIButton

I think most developers have encountered this problem when trying to do localization of an app for multiple languages.

For example, I need to localize the below sentence into different languages, however there are some words that users can click to go to another page. Now, it is very hard to make them still alligned properly as a whole sentence if words in other languages are longer or shorter than English, especially when there are two clickable parts. For the clicking part, I think we can only use UIButton, or are there any other good suggestions? I believe there must be some industrialized way to do this.

"Terms" and "Privacy Policy" are clickable:

enter image description here

Answer Source

So, you can follow the following steps to get your job done.

  1. Create an NSMutableString

    NSString *initString = @"You agree to our terms and policy";
    NSMutableAttributedString *nsms = [[NSMutableAttributedString alloc] initWithString:initString];
    [nsms addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:[initString rangeOfString:@"terms"]];
    [nsms addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:[initString rangeOfString:@"policy"]];
    [nsms addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(0, initString.length)];
    [nsms addAttribute:NSLinkAttributeName value:[NSURL URLWithString:@""] range:[initString rangeOfString:@"policy"]];`
  2. Set the attributed string to the UITextView

    UITextView *TextView = [[UITextView alloc] initWithFrame:CGRectMake(20, 100, [[UIScreen mainScreen] bounds].size.width - 40, 100)];
    TextView.delegate = self;
    TextView.attributedText = nsms;
    TextView.editable = NO;
    [self.view addSubview:TextView];
  3. Inside the delegate function for UITextView

    - (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction {
           // According to range condition/url condition
          [self goToOtherPage];
          return NO;

Here, goToOtherPage is just a custom function in which you can write code for your segue