2012-04-26 57 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