iOS UILabel + UIButton 的本地化最佳实践

iOS Localization Best Practice for UILabel + UIButton

我认为大多数开发人员在尝试针对多种语言对应用程序进行本地化时都遇到过这个问题。

例如,我需要将下面的句子本地化为不同的语言,但是有一些 用户可以单击以转到另一个页面的词。现在,如果其他语言的单词比英语长或短,很难使它们仍然作为一个完整的句子正确对齐,尤其是当有两个可点击部分时。点击部分,我觉得只能用UIButton,或者有什么好的建议吗?我相信一定有一些工业化的方法可以做到这一点。

"Terms" 和 "Privacy Policy" 可点击:

你可以这样做:

let attrString = NSMutableAttributedString(string: "You agree to our ")

let string2 = NSAttributedString(string: "Terms", attributes: [NSLinkAttributeName:"http://www.google.com"])

let string3 = NSAttributedString(string: " and ")

let string4 = NSAttributedString(string: "Conditions", attributes: [NSLinkAttributeName:"http://www.google.com"])

attrString.append(string2)
attrString.append(string3)
attrString.append(string4)

label.attributedText = attrString

编辑:

您可以更好地使用 TTTAttributedLabel。它是 UILabel 的子类。 https://github.com/TTTAttributedLabel/TTTAttributedLabel

更多信息在这里:

因此,您可以按照以下步骤完成您的工作。

  1. 创建一个 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. 将属性字符串设置为 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. 在 UITextView 的委托函数中

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

在这里,goToOtherPage只是一个自定义函数,您可以在其中为您的segue编写代码