2012-04-26 55 views
1

我需要在iphone应用程序中将单词居中放置在UILabel中。我有一串文字太长而不适合标签,所以我想将标签放在特定的单词上并截断两端。例如:这是一个例句。 “大家好,我被困在一个UILabel的长句中。”我想以“卡住”一词为中心,以便UILabel看起来像这样,“......我是卡住试图......”。我发现一个问题的链接有同样的问题,但我无法得到答案为我工作。我对这种编程非常新,所以任何进一步的帮助将非常感谢!提前致谢。这里是另一个问题的链接:iOS: Algorithm to center a word in a sentence inside of a UILabel在UILabel中居中词的算法

回答

3

我刚刚编码并运行此(但没有测试任何边缘情况下)。这个想法是围绕这个单词做一个NSRange以居中,然后在每个方向上对称地扩展这个范围,同时测试截断字符串的像素宽度与标签的宽度。

- (void)centerTextInLabel:(UILabel *)label aroundWord:(NSString *)word inString:(NSString *)string { 

    // do nothing if the word isn't in the string 
    // 
    NSRange truncatedRange = [string rangeOfString:word]; 
    if (truncatedRange.location == NSNotFound) { 
     return; 
    } 

    NSString *truncatedString = [string substringWithRange:truncatedRange]; 

    // grow the size of the truncated range symmetrically around the word 
    // stop when the truncated string length (plus ellipses ... on either end) is wider than the label 
    // or stop when we run off either edge of the string 
    // 
    CGSize size = [truncatedString sizeWithFont:label.font]; 
    CGSize ellipsesSize = [@"......" sizeWithFont:label.font]; // three dots on each side 
    CGFloat maxWidth = label.bounds.size.width - ellipsesSize.width; 

    while (truncatedRange.location != 0 && 
      truncatedRange.location + truncatedRange.length + 1 < string.length && 
      size.width < maxWidth) { 

     truncatedRange.location -= 1; 
     truncatedRange.length += 2; // move the length by 2 because we backed up the loc 
     truncatedString = [string substringWithRange:truncatedRange]; 
     size = [truncatedString sizeWithFont:label.font]; 
    } 

    NSString *ellipticalString = [NSString stringWithFormat:@"...%@...", truncatedString]; 
    label.textAlignment = UITextAlignmentCenter; // this can go someplace else 
    label.text = ellipticalString; 
} 

,并调用它是这样的:

[self centerTextInLabel:self.label aroundWord:@"good" inString:@"Now is the time for all good men to come to the aid of their country"]; 

如果你认为这是一个门将,你可以将其更改为上的UILabel一类方法。

+0

我必须说,这是一个很好的开始。 – CodaFi 2012-04-26 04:36:02

+0

非常好,但是'while'循环不会扩展字符串,直到它超出标签的宽度,然后使用那个稍微太长的字符串?缓存比标签还要短的最长的已知字符串会更好吗?它可能仍然有效,因为'UILabel'可以稍微缩小它的内容以保持一切都在视图中,但这似乎不可靠。或者,也许标签决定它太长,削减省略号,然后添加自己的... – Dondragmer 2012-04-26 04:41:59

+0

是的 - 前卫的案件。可以稍微降低最大宽度阈值。不确定提问者是否可以使用1pt字体自动调整大小。另一个问题是:在宽度可变的字体中,我们可能会扩大范围以围绕不同宽度的每个大小的字符。这里再一次,我们应该适合,但不是像素完美。 – danh 2012-04-26 05:03:48

0

建议:使用两个标签,一个左对齐,一个右对齐。两者应在“外部”(可见)标签边界外部截断,并排放置。分配你的中心词构成两者之间的过渡。

以这种方式,你不会得到完美的居中(它会随着中心词的长度而变化),但它会接近它。

+0

我希望可以看到的单词可能在句子的各个位置。我的文本字符串是从变量字符串中加载的,因此每次都可能会有不同的大小。 – infobug 2012-04-26 04:10:41

+0

@infobug这两个事实并不重要。加载句子,将它分为中心词,并将两个字符串放在不同的标签中 - volia。然而,丹的解决方案更优雅(当然更精细)。 – Matthias 2012-04-26 05:34:46