如何截断选项卡控制器项目的标题



我正在动态创建选项卡,有时项目的标题超过了项目的空间,占用了下一个选项卡的空间。

有人知道如何预防?如何截断名称?

抱歉,我还不能发布照片。

提前感谢!

实际上没有简单的方法可以做到这一点。

您可以将NSString截断为某个定义的宽度(例如"TestBarTitle"->"TestB.."),然后再将其设置为标题:

- (NSString*)stringByTruncatingStringWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode {
    NSMutableString *resultString = [[self mutableCopy] autorelease];
    NSRange range = {resultString.length-1, 1};
    while ([resultString sizeWithFont:font forWidth:FLT_MAX lineBreakMode:lineBreakMode].width > width) {
        // delete the last character
        [resultString deleteCharactersInRange:range];
        range.location--;
        // replace the last but one character with an ellipsis
        [resultString replaceCharactersInRange:range withString:truncateReplacementString];
    }
    return resultString;
}

或者你可以手动实现UITabBar(UIImageView+UIButtons和UILabels),这样你就可以100%控制这个UI元素;

Swift 4.2的解决方案:

var resultString = title
var attributedText = NSAttributedString(string: resultString, attributes: [NSAttributedStringKey.font: font])
while attributedText.boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: 15), options: .usesLineFragmentOrigin, context: nil).size.width > availableWidth {
    // delete last character
    resultString.removeLast(2)
    resultString.append(".")
    attributedText = NSAttributedString(string: resultString, attributes: [NSAttributedStringKey.font: font])
}

最新更新