我的问题是关于作者的标签.一本书可以有多个作者,我希望它的行为如下:
>如果书中有一位作者(‘John Colman’)的标签应为:“John Colman”
>如果书中有多位作者(‘John Colman’,’Bob Night’,’Michael’)标签应为:“John Colman 2位作者”
现在的问题是这个,我希望标签在”之前被截断.因此,例如,如果第一个作者名称很长,让我们说’Benjamin Walter Jackson’,我希望标签看起来像这样:
"Benjamin Walter Ja... +2 authors"
默认行为当然会截断最后的标签,所以它看起来像这样:
"Benjamin Walter Jackson +2 au..."
如果我使用中间截断,则无法保证它会在正确的位置截断标签(在”之前)
我正在寻找一种尽可能高效的方法,而不会影响表格视图的滚动性能.
解决方法 编辑:广泛使用任何“截断位置”字符串的解决方案.以前的版本仅在字符串@“”的实例中截断.编辑允许您定义截断发生的位置.我从this question获得了答案(这是从this site的答案中修改的答案),并根据您的需求量身定制.创建一个新的Nsstring接口,您可以在其中发送要自定义截断的字符串.
注意:此解决方案仅适用于iOS 7.要在iOS 6中使用,请在Nsstring TruncatetoWIDth.m文件中使用sizeWithFont:而不是sizeWithAttributes :.
Nsstring TruncatetoWIDth.h
@interface Nsstring (TruncatetoWIDth)- (Nsstring*)stringByTruncatingAtString:(Nsstring *)string toWIDth:(CGfloat)wIDth withFont:(UIFont *)Font;@end
Nsstring TruncatetoWIDth.m
#import "Nsstring+TruncatetoWIDth.h"#define ellipsis @"…"@implementation Nsstring (TruncatetoWIDth)- (Nsstring*)stringByTruncatingAtString:(Nsstring *)string toWIDth:(CGfloat)wIDth withFont:(UIFont *)Font{ // If the string is already short enough,or // if the 'truncation location' string doesn't exist // go ahead and pass the string back unmodifIEd. if ([self sizeWithAttributes:@{NSFontAttributename:Font}].wIDth < wIDth || [self rangeOfString:string].location == NSNotFound) return self; // Create copy that will be the returned result NSMutableString *truncatedString = [self mutablecopy]; // Accommodate for ellipsis we'll tack on the beginning wIDth -= [ellipsis sizeWithAttributes:@{NSFontAttributename:Font}].wIDth; // Get range of the passed string. Note that this only works to the first instance found,// so if there are multiple,you need to modify your solution NSRange range = [truncatedString rangeOfString:string]; range.length = 1; while([truncatedString sizeWithAttributes:@{NSFontAttributename:Font}].wIDth > wIDth && range.location > 0) { range.location -= 1; [truncatedString deleteCharactersInRange:range]; } // Append ellipsis range.length = 0; [truncatedString replaceCharactersInRange:range withString:ellipsis]; return truncatedString;}@end
使用它:
// Make sure to import the header file where you want to use itmyLabel.text = [@"Benjamin Walker Jackson + 2 authors" stringByTruncatingAtString:@" +" toWIDth:myLabel.frame.size.wIDth withFont:myLabel.Font];// Sample Result: Benjamin Walte... + 2 authors总结
以上是内存溢出为你收集整理的ios – 在特定位置截断UILabel全部内容,希望文章能够帮你解决ios – 在特定位置截断UILabel所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)