gpt4 book ai didi

ios - 在特定位置截断 UILabel

转载 作者:可可西里 更新时间:2023-11-01 05:35:06 26 4
gpt4 key购买 nike

我使用表格 View 来显示图书列表,其中每个单元格都有一个显示书名的 UILabel 和另一个显示图书作者的 UILabel )

我的问题是关于作者标签的。一本书可以有多个作者,我希望它的行为如下:

  • 如果书只有一个作者('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..."  

如果我使用中间截断,则无法保证它会在正确的位置(“+”之前)截断标签

我正在寻找一种方法来做到这一点并且尽可能高效,同时不影响表格 View 的滚动性能。

最佳答案

编辑:将解决方案概括为适用于任何“截断位置”字符串。以前的版本仅在字符串 @"+" 的实例处被截断。 Edit 允许您定义截断发生的位置。


我的答案来自 this question (这是根据 this site 上的答案修改的答案)并根据您的需要进行定制。创建一个新的 NSString 接口(interface),您可以在其中发送要自定义截断的字符串。

注意:此解决方案仅适用于 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 it
myLabel.text = [@"Benjamin Walker Jackson + 2 authors" stringByTruncatingAtString:@" +" toWidth:myLabel.frame.size.width withFont:myLabel.font];
// Sample Result: Benjamin Walte... + 2 authors

关于ios - 在特定位置截断 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24783183/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com