如何将字符串拆分为双行标签

时间:2012-10-24 08:55:27

标签: ios string

我有一个两个单词的字符串,在“&”类型的中间有一个符号在标签的文本中左右“/”,如何在第一行中放置带符号的第一个字符串,在第二行中放置第二个字符串?

这是代码

if(self.labelTitle.text.length> self.labelTitle.bounds.size.width){
     self.labelTitle.numberOfLines =2;

       if([self.labelTitle.text rangeOfString:@"&"].location != NSNotFound){
            NSArray * separateString = [self.labelTitle.text componentsSeparatedByString:@"&"];
            NSString * firstString =[separateString objectAtIndex:0];
            NSString *secondString =[separateString objectAtIndex:1];
            self.labelTitle.text = firstString;
            self.labelTitle.text = secondString;

        }else if ([self.labelTitle.text rangeOfString:@"/"].location != NSNotFound){
            //.....
        }
  }

哪里错了?

1 个答案:

答案 0 :(得分:3)

在代码示例中,您使用firstString覆盖secondString。 您要做的是添加一次text属性并在字符串之间添加\n

if(self.labelTitle.text.length> self.labelTitle.bounds.size.width){
     self.labelTitle.numberOfLines =2;

       if([self.labelTitle.text rangeOfString:@"&"].location != NSNotFound){
            NSArray * separateString = [self.labelTitle.text componentsSeparatedByString:@"&"];
            NSString * firstString =[separateString objectAtIndex:0];
            NSString *secondString =[separateString objectAtIndex:1];
            self.labelTitle.text = [NSString stringWithFormat:@"%@\n%@", firstString, secondString];

        }else if ([self.labelTitle.text rangeOfString:@"/"].location != NSNotFound){
            //.....
        }
  }