Give UITextView a clickable URL link

↘锁芯ラ 提交于 2020-01-04 05:07:12

问题


Hi I've been on this problem for a while now, I read a couple of posts already an I can't understand how to make a clickable UITextView that sends on internet. Here is my code:

func transformText(text: String, underlined: Bool, linkURL: String) -> NSAttributedString {
    let textRange = NSMakeRange(0, text.characters.count)
    let attributedText = NSMutableAttributedString(string: text)
    if underlined{
        attributedText.addAttribute(NSUnderlineStyleAttributeName , value: NSUnderlineStyle.styleSingle.rawValue, range: textRange)
        attributedText.addAttribute(NSUnderlineColorAttributeName , value: UIColor.lightGray, range: textRange)
    }
    attributedText.addAttribute(NSFontAttributeName , value: UIFont(name: "Helvetica-Light", size: 17)!, range: textRange)
    attributedText.addAttribute(NSForegroundColorAttributeName , value: UIColor.lightGray, range: textRange)
    if(linkURL != "")
    {
        let attrib = [NSLinkAttributeName: NSURL(string: linkURL)!]
        attributedText.addAttributes(attrib, range: textRange)
    }
    return attributedText
}

Here is how i call it:

TextContent.attributedText = transformText(text: self.TelBox.TextContent.text, underlined: true, linkURL: "https://www.google.fr")`

Thanks in advance


回答1:


Select the UITextView on storyboard and go to 'Show the Attributes inspector', then in 'behavior' unselects 'Editable' and in 'Data Detector' select 'Link'. Then go to 'Sohw the Identity inspector' and in 'traits' select 'Link' and 'Selected'.




回答2:


The fact is you want to make UITextView to make clickable requires you to make UITextView non editable because when you click on text it will lunch keyboard. To prevent this you can use

textView.isEditable = false

Hope it helps.




回答3:


Make sure you've also enabled data type detection. For hyperlinks:

theTextView.dataDetectorTypes = [.link]



回答4:


You must set editable YES or set selectable YES

NSString *text = @"this is google web link";
UITextView *textView = [[UITextView alloc] init];

NSDictionary *dictionary = @{NSFontAttributeName:[UIFont systemFontOfSize:10],NSForegroundColorAttributeName:[UIColor whiteColor]};
NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:text attributes:dictionary];

textView.attributedText = attributeStr;

[attributeStr addAttributes:@{NSLinkAttributeName: [NSURL URLWithString:@"http://www.google.com"]} range:[_readMessage rangeOfString:@"google web link"]];
textView.attributedText = attributeStr;

textView.editable = NO;
textView.selectable = YES;
textView.delegate = self;

google link will reponse by delegate

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange


来源:https://stackoverflow.com/questions/46547066/give-uitextview-a-clickable-url-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!