代码之家  ›  专栏  ›  技术社区  ›  VRAwesome

在UILabel中设置文本(带有表情符号、特殊字符、链接),链接应该可以单击

  •  1
  • VRAwesome  · 技术社区  · 7 年前

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

    但现在我想把网址放进去 应该是可点击的,所以当我们点击网址,它应该是在打开 Safari

    enter image description here

    注意:由于文本来自服务器,所以我不知道网址的位置,也会有多个网址。

    怎么办?我已经找过了,但没有找到解决办法。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Mike Critchley    7 年前

    上个月我在另一个项目中需要这种链接文本。我创建了一个自定义UITableViewCell,其中有一个UITextView对象,子类化为自定义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;
    }
    

    对于文本视图,如果关闭滚动,您会发现使用自动布局更容易。

    #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

    推荐文章