我正在动态创建tabbaritems,有时项目的标题超出了项目的空间,它占用了下一个tabbaritem的空间。
有人知道如何预防吗?如何截断名称?
很抱歉,但我还不能发布照片。
提前致谢!
答案 0 :(得分:2)
实际上没有简单的方法可以做到。
在将NSString设置为标题之前,您可以将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元素;
答案 1 :(得分:0)
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])
}