在我的一个应用程序中,调用了 API 并从服务器获取数据。其中有文本 - 包含表情符号、特殊字符、URL 等。
不是在我的 UITableViewCell
中,我有简单的 UILabel
并将文本设置为标签。
到目前为止一切正常。
但现在我希望 UILabel
中的 URL 应该是可点击的,所以当我们点击 URL 时它应该在 Safari
中打开。
注意:由于文本来自服务器,所以我不知道 URL 的位置,并且还会有多个 URL。
为此要做什么?我已搜索但未找到解决方案。
最佳答案
我上个月的另一个项目需要这种链接文本。我在单元格中创建了一个带有 UITextView 对象的自定义 UITableViewCell,子类化为自定义 UITextView 子类。我刚刚做了一个快速演示项目,现在把它放在 git 上供你使用。请随意使用它。
github.com/fareast555/MPC_LinkedTextView
使用文本链接的基本秘诀是可变文本中的 NSLinkAttributeName 属性,并告诉系统处理链接。
- (void)updateTextViewWithFullText:(NSString *)fullText linkTriggerText:(NSString *)triggerText linkURLString:(NSString *)urlString
{
//Create a mutable string based on the full text
NSMutableAttributedString *mutableString = [[NSMutableAttributedString alloc]initWithString:fullText attributes:nil];
//Add the link attribute across the range of the target text
[mutableString addAttribute:NSLinkAttributeName value:urlString range:[fullText rangeOfString:triggerText]];
//Add any other font or color bling as needed
[mutableString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:18 weight:UIFontWeightMedium] range:NSMakeRange(0, [fullText length])];
//Set the mutable text to the textfield
[self setAttributedText: mutableString];
}
#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction
{
return YES;
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
return NO;
}
对于 TextView ,如果关闭滚动,您会发现使用自动布局会更容易。
#pragma mark - Configure
- (void)_configureTextView
{
self.delegate = self;
[self setEditable:NO];
[self setSelectable:YES];
[self setScrollEnabled:NO];
[self setUserInteractionEnabled:YES];
[self setDataDetectorTypes:UIDataDetectorTypeLink];
self.scrollIndicatorInsets = UIEdgeInsetsZero;
}
关于ios - 在 UILabel 中设置文本(带有表情符号、特殊字符、链接),并且链接应该是可点击的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52696318/