【问题标题】:How to change truncate characters in UILabel?如何更改 UILabel 中的截断字符?
【发布时间】:2011-06-15 04:07:30
【问题描述】:

UILabel 的文本被截断时,默认插入 3 个点。 是否可以更改这些字符或禁用它们?

【问题讨论】:

  • 仅供参考,三个小点被称为ellipsis

标签: iphone uilabel truncation


【解决方案1】:

我编写了一个自定义截断类,您可以随时将其弹出到您的代码中。只需使用下面的这种方法。如果发生截断,它将返回 true,如果您只想使用标签默认帧宽度,则 MaxWidth 可以保留为 0。将 maxWidth 设置为小于框架宽度的值,以在其框架范围内缩短它。

Swift 2(带有一些用于转换的 swift 3 cmets)

用法:

Truncater.replaceElipsis(forLabel: label, withString: "???")
let didTruncate = Truncater.replaceElipsis(forLabel: label, withString: "1234", andMaximumWidth: 50) //maxWidth is not number of chars, but label width in CGFloat

类:

import UIKit

class Truncater {

    class func replaceElipsis(forLabel label:UILabel, withString replacement:String) -> Bool {
        return replaceElipsis(forLabel: label, withString: replacement, andMaximumWidth:0)
    }

    class func replaceElipsis(forLabel label:UILabel, withString replacement:String, andMaximumWidth width:CGFloat) -> Bool {

        if(label.text == nil){
            return false
        }

        let origSize = label.frame;
        var useWidth = width

        if(width <= 0){
            useWidth = origSize.width //use label width by default if width <= 0
        }

        label.sizeToFit()
        let labelSize = label.text!.sizeWithAttributes([NSFontAttributeName: label.font]) //.size(attributes: [NSFontAttributeName: label.font]) for swift 3

        if(labelSize.width > useWidth){

            let original = label.text!;
            let truncateWidth = useWidth;
            let font = label.font;
            let subLength = label.text!.characters.count

            var temp = label.text!.substringToIndex(label.text!.endIndex.advancedBy(-1)) //label.text!.substring(to: label.text!.index(label.text!.endIndex, offsetBy: -1)) for swift 3
            temp = temp.substringToIndex(temp.startIndex.advancedBy(getTruncatedStringPoint(subLength, original:original, truncatedWidth:truncateWidth, font:font, length:subLength)))
            temp = String.localizedStringWithFormat("%@%@", temp, replacement)

            var count = 0

            while temp.sizeWithAttributes([NSFontAttributeName: label.font]).width > useWidth {

                count+=1

                temp = label.text!.substringToIndex(label.text!.endIndex.advancedBy(-(1+count)))
                temp = temp.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) //remove this if you want to keep whitespace on the end
                temp = String.localizedStringWithFormat("%@%@", temp, replacement)
            }

            label.text = temp;
            label.frame = origSize;
            return true;
        }
        else {

            label.frame = origSize;
            return false
        }
    }

    class func getTruncatedStringPoint(splitPoint:Int, original:String, truncatedWidth:CGFloat, font:UIFont, length:Int) -> Int {

        let splitLeft = original.substringToIndex(original.startIndex.advancedBy(splitPoint))

        let subLength = length/2

        if(subLength <= 0){
            return splitPoint
        }

        let width = splitLeft.sizeWithAttributes([NSFontAttributeName: font]).width

        if(width > truncatedWidth) {
            return getTruncatedStringPoint(splitPoint - subLength, original: original, truncatedWidth: truncatedWidth, font: font, length: subLength)
        }
        else if (width < truncatedWidth) {
            return getTruncatedStringPoint(splitPoint + subLength, original: original, truncatedWidth: truncatedWidth, font: font, length: subLength)
        }
        else {
            return splitPoint
        }
    }
}

目标 C

+ (bool) replaceElipsesForLabel:(UILabel*) label With:(NSString*) replacement MaxWidth:(float) width 

类:

//=============================================Header=====================================================
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface CustomTruncater : NSObject

+ (bool) replaceElipsesForLabel:(UILabel*) label With:(NSString*) replacement MaxWidth:(float) width;

@end

//========================================================================================================

#import "CustomTruncater.h"

@implementation CustomTruncater

static NSString *original;
static float truncateWidth;
static UIFont *font;
static int subLength;

+ (bool) replaceElipsesForLabel:(UILabel*) label With:(NSString*) replacement MaxWidth:(float) width {

CGRect origSize = label.frame;

float useWidth = width;

if(width <= 0)
    useWidth = origSize.size.width; //use label width by default if width <= 0

[label sizeToFit];
CGSize labelSize = [label.text sizeWithFont:label.font];

if(labelSize.width > useWidth) {

    original = label.text;
    truncateWidth = useWidth;
    font = label.font;
    subLength = label.text.length;

    NSString *temp = [label.text substringToIndex:label.text.length-1];
    temp = [temp substringToIndex:[self getTruncatedStringPoint:subLength]];
    temp = [NSString stringWithFormat:@"%@%@", temp, replacement];

    int count = 0;

    while([temp sizeWithFont:label.font].width > useWidth){

        count++;

        temp = [label.text substringToIndex:(label.text.length-(1+count))];
        temp = [temp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; //remove this if you want to keep whitespace on the end
        temp = [NSString stringWithFormat:@"%@%@", temp, replacement];
    }

    label.text = temp;
    label.frame = origSize;
    return true;
}
else {
    label.frame = origSize;
    return false;
}
}

+ (int) getTruncatedStringPoint:(int) splitPoint {

NSString *splitLeft = [original substringToIndex:splitPoint];
subLength /= 2;

if(subLength <= 0)
    return splitPoint;

if([splitLeft sizeWithFont:font].width > truncateWidth){
    return [self getTruncatedStringPoint:(splitPoint - subLength)];
}
else if ([splitLeft sizeWithFont:font].width < truncateWidth) {
    return [self getTruncatedStringPoint:(splitPoint + subLength)];
}
else {
    return splitPoint;
}
}

@end

【讨论】:

    【解决方案2】:

    查看-[UILabel setLineBreakMode:]UILineBreakModeCharacterWrap-[UILabel lineBreakMode] 的默认值是UILineBreakModeTailTruncation,导致末尾有省略号。

    【讨论】:

      【解决方案3】:

      正如 Javanator 所说,您必须自己进行截断。你应该使用 UIKit 上的sizeWithFont:forWidth:lineBreakMode: 消息添加到NSString 类以获取具有特定字体的字符串的宽度。这将处理所有类型的字体。

      Link

      【讨论】:

        【解决方案4】:

        你也可以设置

        [lbl setAdjustsFontSizeToFitWidth:YES];
        

        这样就不需要截断文本,您可以在label 上显示完整的文本。

        【讨论】:

        • 不起作用,因为我使用的是自定义字体(在 UIAppFonts-key 中设置)
        【解决方案5】:

        为什么你不编码来计算字符串的长度,如果它超出了视图,则生成它的子字符串。或做任何你想做的事 这是一种原始但有效的方法

        【讨论】:

        • 我并不是说要使用它来制作任何标准 api。我猜字体规范将根据要求进行修复。
        猜你喜欢
        • 2012-12-04
        • 1970-01-01
        • 2016-06-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多