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

时间:2016-10-28 18:29:27

标签: ios localization nsstring

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

例如,我需要将下面的句子本地化为不同的语言,但是有一些单词可供用户点击转到另一个页面。现在,如果其他语言中的单词比英语更长或更短,则很难使它们作为整个句子正确对齐,尤其是当有两个可点击的部分时。对于点击部分,我认为我们只能使用 UIButton ,还是有其他好的建议?我相信必须有一些工业化的方法来做到这一点。

"条款"和"隐私政策"可点击:

enter image description here

2 个答案:

答案 0 :(得分:1)

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

  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:@"http://stackoverflow.com/questions/40311151/ios-localization-best-practice-for-uilabel-uibutton"] 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;
    }
    
  4. 在这里,goToOtherPage只是一个自定义函数,您可以在其中编写segue的代码

答案 1 :(得分:0)

您可以这样做:

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

此处有更多信息:Make Clickable UILabel Using Swift