iOS   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ios – UITextView中链接的不同样式大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我希望我的UITextView包括纯文本,链接,电话号码和其他UIDataDetectorTypes.例如,纯文本 – 黑色,链接 – 带下划线的蓝色,主题标签 – 绿色.所以,我解析文本并添加主题标签链接

[attributedString addAttribute:NSLinkAttributENAME value:[NSString StringWithFormat:@"hashtag://%@",hashtag] range:range];

如果dataDetectorTypes设置为UIDataDetectorTypeAll,则认情况下会检测其他链接.但是如何更改主题标签链接样式?

解决方法

您可以使用官方Twitter库跟踪名为 twitter text主题标签以及 TTTAttributedLabel.

Hashtags有特殊条件,这些条件可能超过前面带#的字母数字字符.

twitter文本库将自动为您找到主题标签的范围,然后您应该能够使用TTTAttributedLabel对其进行格式化.

以下是两个库的示例实现.

- (void)scanForHashtag:(NSArray *)hashtags fromLabel:(id)sender
{
    TTTAttributedLabel *label = (TTTAttributedLabel *)sender;

    for (TwitterTextEntity *entity in hashtags) {
        UIFont *boldSystemFont = [UIFont fontWithName:@"Helvetica-Bold" size:12];
        CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)boldSystemFont.fontName,boldSystemFont.pointSize,null);
        NSArray *keys = [[NSArray alloc] initWithObjects:(id)kCTForegroundColorAttributename,(id)kCTUnderlinestyleAttributename,(NSString *)kCTFontAttributename,nil];
        UIColor *hashtagColor;
        hashtagColor = [UIColor greenColor];
        NSArray *objects = [[NSArray alloc] initWithObjects:hashtagColor,[NSnumber numberWithInt:kCTUnderlinestyleNone],(__bridge id)font,nil];
        NSDictionary *linkAttributes = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
        label.linkAttributes = linkAttributes;

        NSString *hashtag = [label.text subStringWithRange:entity.range];

        if (entity.type == 2) { //Hashtag
            [label addLinkToPhonenumber:hashtag withRange:entity.range];
        } else if (entity.type == 0) { //URL
            NSURL *url = [NSURL URLWithString:[label.text subStringWithRange:entity.range]];
            [label addLinkToURL:url withRange:entity.range];
        }
    }
}

- (void)attributedLabel:(TTTAttributedLabel *)label didSELEctLinkWithPhonenumber:(NSString *)phonenumber
{

    //Do whatever you need when the hashtag is tapped.
}

[self scanForHashtag:[TwitterText hashtagsIntext:@"The text that contains the tweet with hashtags." checkingURLOverlap:NO] fromLabel:yourLabel]; //yourLabel is the label that contains the text so it would be formatted.

编辑UITextView

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
[attributedString addAttribute:NSBACkgroundColorAttributename
                   value:[UIColor yellowColor]
                   range:entity.range];

大佬总结

以上是大佬教程为你收集整理的ios – UITextView中链接的不同样式全部内容,希望文章能够帮你解决ios – UITextView中链接的不同样式所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。