ios - 在 UILabel 中设置文本(带有表情符号、特殊字符、链接),并且链接应该是可点击的

标签 ios objective-c xcode url uilabel

在我的一个应用程序中,调用了 API 并从服务器获取数据。其中有文本 - 包含表情符号、特殊字符、URL 等。

不是在我的 UITableViewCell 中,我有简单的 UILabel 并将文本设置为标签。 到目前为止一切正常。

但现在我希望 UILabel 中的 URL 应该是可点击的,所以当我们点击 URL 时它应该在 Safari 中打开。

enter image description here

注意:由于文本来自服务器,所以我不知道 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;
}

Screenshot of table view

关于ios - 在 UILabel 中设置文本(带有表情符号、特殊字符、链接),并且链接应该是可点击的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52696318/

相关文章:

iOS IAP - 沙盒用户是否从实时商店购买?

ios - 如何在 xcode 代码中显示图像标题而不是图标?

ios - 将 SpriteKit 添加到空应用程序

ios - #import <libxml/tree.h> xcode 更新后找不到文件

ios - 如何在IOS中检查自动对焦是否仍在进行?

ios - UIStackView 作为 XIB 的 Root View

objective-c - 迪尔德 : Symbol not found: __NSConcreteGlobalBlock after updating to OSX 10. 8

C++ 和 Swift 彼此不喜欢

iOS - NSFIleManager - 如何处理磁盘空间不足

ios - 界面 View : addConstraint fails with EXC_BAD_INSTRUCTION unless no-op constraints() is called first