0

私のコードで 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ライブラリで正しく使用していますか?

編集:

「機能しない」ということは、下線付きのテキストがグレーのままで、上で設定したように赤ではないということです。

4

1 に答える 1

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ソースコードを変更してデフォルトのリンク色を変更することです。

于 2015-01-27T09:46:56.227 に答える