gpt4 book ai didi

ios - UITextView 中链接的不同样式

转载 作者:可可西里 更新时间:2023-11-01 05:43:57 24 4
gpt4 key购买 nike

我希望我的 UITextView 包含纯文本、链接、电话号码和其他 UIDataDetectorTypes。例如,纯文本 - 黑色,链接 - 带下划线的蓝色,主题标签 - 绿色。因此,我解析文本并添加指向主题标签的链接:

[attributedString addAttribute:NSLinkAttributeName value:[NSString stringWithFormat:@"hashtag://%@", hashtag] range:range];

如果 dataDetectorTypes 设置为 UIDataDetectorTypeAll,则默认检测其他链接。但是如何更改主题标签的链接样式?

最佳答案

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

主题标签有特殊条件,这些条件可能不仅仅是以# 开头的字母数字字符。

twitter-text 库会自动为您找到主题标签的范围,然后您应该能够使用 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 中链接的不同样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29228654/

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