【问题标题】:Can't set linkAttributes on TTTAttributedLabel无法在 TTTAttributedLabel 上设置 linkAttributes
【发布时间】:2015-01-27 17:46:56
【问题描述】:

在我的代码中使用 TTTAttributedLabel:

NSString *contentText = @"some text here foo bar";

[self.content setText:contentText afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
    return mutableAttributedString;
}];
self.content.linkAttributes = @{ NSForegroundColorAttributeName: [UIColor redColor],
                               NSUnderlineStyleAttributeName: [NSNumber numberWithInt:NSUnderlineStyleSingle] };
NSRange range = [self.content.text rangeOfString:@"foo bar"];
[self.content addLinkToURL:[NSURL URLWithString:@"action://load-foo"] withRange:range];
[self.content setNeedsDisplay];

在点击范围文本和执行操作方面,一切都很完美,但是,唯一似乎不起作用的是文本颜色。我是否在库中正确使用了NSForegroundColorAttributeName

编辑:

“不起作用”是带下划线的文本保持灰色,而不是像我上面设置的那样为红色。

【问题讨论】:

  • 您是否在低于 6 的 iOS 上进行部署?
  • @Andrea Nope,iOS8 及以上
  • 使用 NSAttributeString 和默认文本渲染对象,用 UITextField 或 TextView 替换标签并检查数据检测器会容易得多
  • 您应该在设置文本或向标签添加链接之前分配linkAttributes
  • 这最后的评论实际上是正确的答案,谢谢

标签: ios objective-c tttattributedlabel


【解决方案1】:

我之前也遇到过同样的问题,纠结了好久还是没找到原因,放弃了你说的解决方法,想出了如下方法:

NSString *contentText = @"some text here foo bar";
NSString* matchString = @"foo bar";
NSRegularExpression *mentionExpression = [NSRegularExpression regularExpressionWithPattern:matchString options:NO error:nil];
NSArray *matches = [mentionExpression matchesInString:contentText
                                                  options:0
                                                    range:NSMakeRange(0, [contentText length])];
    for (NSTextCheckingResult *match in matches) {
        NSRange matchRange = [match rangeAtIndex:0];
        NSString *mentionString = [contentText substringWithRange:matchRange];
        NSArray *keys = @[(id) kCTForegroundColorAttributeName, (id) kCTUnderlineStyleAttributeName
        ];
        NSArray *objects = @[[UIColor redColor], @(kCTUnderlineStyleNone)];
        NSDictionary *linkAttributes = @{keys : objects};

        [self.yourlabel addLinkWithTextCheckingResult:match attributes:linkAttributes];
    }
    self.yourlabel.delegate = self;

//Then overwrite the delegate method for the link click actions
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithTextCheckingResult:(NSTextCheckingResult *)result {
    //do whatever you need
}

此解决方案的优点是您可以根据需要添加任意数量的自定义链接样式。

当然,如果您坚持使用addLinkToURL,另一种可能的解决方案是更改TTTAttributedLabel源代码以更改默认链接颜色。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 2015-09-19
    • 1970-01-01
    • 2011-12-13
    • 2017-08-14
    相关资源
    最近更新 更多