在UITextView中使超链接可点击是很简单的。您只需在IB中的视图上设置“检测链接”复选框,它就会检测HTTP链接并将其转换为超链接。

然而,这仍然意味着用户看到的是“原始”链接。RTF文件和HTML都允许你设置一个用户可读的字符串,“后面”有一个链接。

将带属性的文本安装到文本视图(或UILabel或UITextField)是很容易的。但是,当带有属性的文本包含链接时,它是不可点击的。

是否有一种方法使用户可读的文本点击在UITextView, UILabel或UITextField?

在SO上的标记是不同的,但这里是大致的思想。我想要的是这样的文本:

这个变形是由Face Dancer生成的,点击在应用程序商店中查看。

我唯一能得到的是:

这个变形是由Face Dancer生成的,点击http://example.com/facedancer在应用商店中查看。


当前回答

Swift版本:

    // Attributed String for Label
    let plainText = "Apkia"
    let styledText = NSMutableAttributedString(string: plainText)
    // Set Attribuets for Color, HyperLink and Font Size
    let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(14.0), NSLinkAttributeName:NSURL(string: "http://apkia.com/")!, NSForegroundColorAttributeName: UIColor.blueColor()]
    styledText.setAttributes(attributes, range: NSMakeRange(0, plainText.characters.count))
    registerLabel.attributedText = styledText

其他回答

Swift版本:

    // Attributed String for Label
    let plainText = "Apkia"
    let styledText = NSMutableAttributedString(string: plainText)
    // Set Attribuets for Color, HyperLink and Font Size
    let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(14.0), NSLinkAttributeName:NSURL(string: "http://apkia.com/")!, NSForegroundColorAttributeName: UIColor.blueColor()]
    styledText.setAttributes(attributes, range: NSMakeRange(0, plainText.characters.count))
    registerLabel.attributedText = styledText

只需为UITextView找到一个无代码的解决方案:

启用检测->链接选项,URL和电子邮件也将被检测和点击!

我也有类似的需求,最初我使用UILabel,然后我意识到UITextView更好。我使UITextView行为像UILabel通过禁用交互和滚动,并为NSMutableAttributedString做了一个类别方法来设置链接到文本,就像Karl所做的一样(+1)这是我的obj c版本

-(void)setTextAsLink:(NSString*) textToFind withLinkURL:(NSString*) url
{
    NSRange range = [self.mutableString rangeOfString:textToFind options:NSCaseInsensitiveSearch];

    if (range.location != NSNotFound) {

        [self addAttribute:NSLinkAttributeName value:url range:range];
        [self addAttribute:NSForegroundColorAttributeName value:[UIColor URLColor] range:range];
    }
}

您可以使用下面的委托来处理该操作

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)url inRange:(NSRange)characterRange
{
    // do the task
    return YES;
}

使用NSMutableAttributedString。

NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:@"Google"];
[str addAttribute: NSLinkAttributeName value: @"http://www.google.com" range: NSMakeRange(0, str.length)];
yourTextView.attributedText = str;

编辑:

这不是直接关于这个问题,只是澄清一下,UITextField和UILabel不支持打开url。如果你想使用UILabel链接,你可以检查TTTAttributedLabel。

此外,你应该设置你的UITextView的dataDetectorTypes值为UIDataDetectorTypeLink或UIDataDetectorTypeAll以在单击时打开url。或者你也可以按照评论中的建议使用委托方法。

使用UITextView并为Link设置dataDetectorTypes。

是这样的:

testTextView.editable = false 
testTextView.dataDetectorTypes = .link

如果你想检测链接,电话号码,地址等

testTextView.dataDetectorTypes = .all