簡體   English   中英

如果UILabel的內容不適合,請更改文本末尾的默認“...”

[英]Change the default '…' at the end of a text if the content of a UILabel doesn't fit

我的iPhone項目中有一個UILabel,它有一個固定的寬度和高度,但它的內容可能會根據用戶的不同而有所不同。 有時文本對UILabel來說很大,那就是當字符串:'...'被添加到行尾時。 我想知道我是否可以將此字符串更改為其他內容,例如:'(more)'。

謝謝!

不幸的是,似乎這樣的選項不包含在iOS上,根據這個類似的問題: 如何在UILabel中更改截斷字符?

但是,正如上述問題中的答案所述,這可以自己輕松完成。 您真正需要做的就是找到字符串被截斷的位置並減去所選結束字符所需的數量。 然后將余數放在一個單獨的字符串中。

對於這種方法,這個答案也很有用:

正如Javanator所說,你必須自己截斷。 你shuld使用sizeWithFont:forWidth:lineBreakMode:消息對UIKit添加到NSString類以獲取具有特定字體的字符串的寬度。 這將處理所有類型的字體。

我認為這是一個有趣的問題,因此構建並且幾乎沒有測試過這個......

- (void)setText:(UILabel *)label withText:(NSString *)text andTruncationSuffix:(NSString *)truncationSuffix {

    // just set the text if it fits using the minimum font
    //
    CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:label.minimumFontSize]];
    if (size.width <= label.bounds.size.width) {
        label.text = text;
        return;
    }

    // build a truncated version of the text (using the custom truncation text)
    // and shrink the truncated text until it fits
    NSInteger lastIndex = text.length;
    CGFloat width = MAXFLOAT;

    NSString *subtext, *ellipticalText;

    while (lastIndex > 0 && width > label.bounds.size.width)  {
        subtext = [text substringToIndex:lastIndex];
        ellipticalText = [subtext stringByAppendingString:truncationSuffix];
        width = [ellipticalText sizeWithFont:[UIFont systemFontOfSize:label.minimumFontSize]].width;
        lastIndex--;
    }
    label.text = ellipticalText;
}

像這樣稱呼它:

[self setText:self.label withText:@"Now is the time for all good men to come to the aid of their country" andTruncationSuffix:@" more"];

如果這適合您,您可以考慮添加UILabel的子類,使用它來覆蓋setText:方法,並添加名為truncatedSuffix的屬性。

如果您使用的是iOS版本> 8.0,則可以使用ResponsiveLabel 在這里,您可以提供自定義截斷標記以及定義操作以使其可插入。

NSString *expansionToken = @"Read More ...";
NSString *str = @"Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
NSMutableAttributedString *attribString = [[NSMutableAttributedString alloc]initWithString:kExpansionToken attributes:@{NSForegroundColorAttributeName:[UIColor blueColor],NSFontAttributeName:self.customLabel.font}];
[self.customLabel setAttributedTruncationToken:attribString withAction:^(NSString *tappedString) {
 NSLog(@"Tap on truncation text");
}];
[self.customLabel setText:str withTruncation:YES];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM