【问题标题】:Replace the truncation ellipsis of UILabel in iOS 7在 iOS 7 中替换 UILabel 的截断省略号
【发布时间】:2014-02-15 10:08:23
【问题描述】:

如何将 iOS 7 中 UILabel 的截断省略号(“...”)替换为另一个 归因 字符?例如,带有彩色的“>”。

我希望 Text Kit 的 NSLayoutManager 可以实现这一点,但如果 UILabel 使用它,它似乎不会将其公开。

另外,我可以安全地假设在每个本地化中都使用省略号作为截断字符吗?也许不同的语言有不同的截断字符。

【问题讨论】:

标签: ios ios7 uilabel truncation textkit


【解决方案1】:

我建议您使用TTTAttributedLabel,只需将属性“attributedTruncationToken”设置为您的自定义字符串。

【讨论】:

  • 我不知道 TTTAttributedLabel 有这个功能 - 很棒的解决方案
【解决方案2】:

我认为它无法让您访问此内容。我想你会手动处理它。例如,使用 TextKit 确定字符串的大小,如果它不适合可用区域,请自行截断并附加“>”,然后将新字符串放入标签中。

NSAttributedString 有获取字符串大小的方法。

如果您需要更多详细信息,请告诉我..?

【讨论】:

  • 谢谢。我对如何手动执行此操作有所了解,但始终感谢更多细节。特别是如果您使用 Text Kit,因为周围的大多数其他代码示例都没有更新到最新的 iOS 7 API。
  • 说实话,我今天下午给你举个例子……你反对使用CoreText吗?
  • 不着急。如果相同的功能在更高的抽象级别上可用,我更喜欢 Text Kit。
【解决方案3】:

我认为您可以在 Fonix 提供的 -replaceElipsesForLabel 方法中进行一些自定义,以获得您想要的结果。

【讨论】:

  • 谢谢。我没有看到这个问题。有点重复,但我想专注于 iOS 7。如果你认为这两个不值得,请随意投票。关于您建议的解决方案,我希望避免复制截断逻辑,因为有很多不同的情况需要考虑(而 Fonix 的答案没有。)
【解决方案4】:

我已经写了一个方法来做到这一点,并在 iOS7 中工作

-(void)setCustomEllipsis:(NSString*)customEllipsis inLabel:(UILabel*)label with:(NSString*)string{

//Replace the ellipsis
NSMutableString* result = [[NSMutableString alloc] initWithString:@""];
NSArray* strings = [string componentsSeparatedByString:@" "];
for (NSString* s in strings) {
    CGRect newSize = [[NSString stringWithFormat:@"%@%@%@",result,s,customEllipsis] boundingRectWithSize:CGSizeMake(label.frame.size.width,0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:label.font} context:nil];
    if (newSize.size.height < label.frame.size.height) {
        [result appendString:s];
        [result appendString:@" "];
    }else{
        [result appendString:customEllipsis];
        break;
    }
}
[label setText:result];

//Set different font to the ellipsis
const CGFloat fontSize = 13;
UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize];
UIFont *regularFont = [UIFont systemFontOfSize:fontSize];
UIColor *foregroundColor = [UIColor lightGrayColor];

NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:regularFont, NSFontAttributeName,foregroundColor, NSForegroundColorAttributeName, nil];
NSDictionary *subAttrs = [NSDictionary dictionaryWithObjectsAndKeys:boldFont, NSFontAttributeName, nil];
const NSRange range = [label.text rangeOfString:customEllipsis];

NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:result
                                           attributes:attrs];
[attributedText setAttributes:subAttrs range:range];


[label setAttributedText:attributedText];
}

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2015-03-11
    • 2011-09-17
    • 2016-08-18
    • 2015-03-25
    • 2011-11-23
    相关资源
    最近更新 更多