如何让UITextView检测网站,邮件和电话号码的链接

时间:2009-06-15 09:36:12

标签: ios objective-c hyperlink uitextview

我有一个UITextView对象。 UIView中的文字有电话号码,邮件链接,网站链接。我想将它们显示为具有以下功能的链接。

当有人点击URL时 - Safari应该打开网站。 当有人点击电子邮件链接时 - 邮件应该打开我的地址到字段 当有人点击电话号码时 - 电话应用程序应拨打号码

以前是否有人这样做过或者知道如何处理它?<​​/ p>

谢谢, AJ

7 个答案:

答案 0 :(得分:96)

如果您使用的是OS3.0

你可以像下面这样做

textview.editable = NO;
textview.dataDetectorTypes = UIDataDetectorTypeAll;

答案 1 :(得分:18)

关于检测电子邮件地址的注意事项:必须安装邮件应用程序(它不在iOS模拟器上),以便电子邮件链接打开邮件撰写屏幕。

答案 2 :(得分:11)

Swift 3.0 +

从swift 3.0开始,如果您想以编程方式执行此操作,请使用以下代码。

textview.isEditable = false
textview.dataDetectorTypes = .all

或者如果你有故事板

enter image description here

答案 3 :(得分:3)

虽然问题是超级老。 如果有人面临同样的问题,

它也可以用作 UILabel 。虽然 以下解决方案将完成这项工作: [不需要任何库..]

所以我使用了 MFMailcomposer() UITexView [代码在Swift 3.0中 - Xcode 8.3.2]

100%崩溃证明和工作代码处理所有角落案件。 = d

第1步。

import MessageUI

第2步。添加代理

class ViewController: UITextViewDelegate, MFMailComposeViewControllerDelegate{

第3步。从StoryBoard添加textView IBOutlet

@IBOutlet weak var infoTextView: UITextView!

第4步。在viewDidload()

中调用以下方法
func addInfoToTextView()  {
    let attributedString = NSMutableAttributedString(string: "For further info call us on : \(phoneNumber)\nor mail us at : \(email)")
    attributedString.addAttribute(NSLinkAttributeName, value: "tel://", range: NSRange(location: 30, length: 10))
    attributedString.addAttribute(NSLinkAttributeName, value: "mailto:", range: NSRange(location: 57, length: 18))
    self.infoTextView.attributedText = attributedString
    self.infoTextView.linkTextAttributes = [NSForegroundColorAttributeName:UIColor.blue, NSUnderlineStyleAttributeName:NSNumber(value: 0)]
    self.infoTextView.textColor = .white
    self.infoTextView.textAlignment = .center
    self.infoTextView.isEditable = false
    self.infoTextView.dataDetectorTypes = UIDataDetectorTypes.all
    self.infoTextView.delegate = self
}

第5步。实现TextView的委托方法

@available(iOS, deprecated: 10.0)
func textView(_ textView: UITextView, shouldInteractWith url: URL, in characterRange: NSRange) -> Bool {
    if (url.scheme?.contains("mailto"))! && characterRange.location > 55{
        openMFMail()
    }
    if (url.scheme?.contains("tel"))! && (characterRange.location > 29 && characterRange.location < 39){
        callNumber()
    }
    return false
}

//For iOS 10
@available(iOS 10.0, *)
func textView(_ textView: UITextView, shouldInteractWith url: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    if (url.scheme?.contains("mailto"))! && characterRange.location > 55{
        openMFMail()
    }
    if (url.scheme?.contains("tel"))! && (characterRange.location > 29 && characterRange.location < 39){
        callNumber()
    }
    return false
}

第6步。编写帮助程序方法以打开MailComposer并调用应用程序

func callNumber() {
    if let phoneCallURL = URL(string: "tel://\(phoneNumber)")
    {
        let application:UIApplication = UIApplication.shared
        if (application.canOpenURL(phoneCallURL))
        {
            let alert = UIAlertController(title: "Call", message: "\(phoneNumber)", preferredStyle: UIAlertControllerStyle.alert)
            if #available(iOS 10.0, *)
            {
                alert.addAction(UIAlertAction(title: "Call", style: .cancel, handler: { (UIAlertAction) in
                    application.open(phoneCallURL, options: [:], completionHandler: nil)
                }))
            }
            else
            {
                alert.addAction(UIAlertAction(title: "Call", style: .cancel, handler: { (UIAlertAction) in
                    application.openURL(phoneCallURL)
                }))
            }

            alert.addAction(UIAlertAction(title: "cancel", style: .default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
    }
    else
    {
        self.showAlert("Couldn't", message: "Call, cannot open Phone Screen")
    }
}
func openMFMail(){
    let mailComposer = MFMailComposeViewController()
    mailComposer.mailComposeDelegate = self
    mailComposer.setToRecipients(["\(email)"])
    mailComposer.setSubject("Subject..")
    mailComposer.setMessageBody("Please share your problem.", isHTML: false)
    present(mailComposer, animated: true, completion: nil)

}

第7步。编写MFMailComposer的委托方法

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
    switch result {
    case .cancelled:
        print("Mail cancelled")
    case .saved:
        print("Mail saved")
    case .sent:
        print("Mail sent")
    case .failed:
        print("Mail sent failure: \(String(describing: error?.localizedDescription))")
    default:
        break
    }
    controller.dismiss(animated: true, completion: nil)
}
  

你做完了...... = D

以下是上述代码的swift文件: textViewWithEmailAndPhone.swift

  

将以下属性设置为将其用作UILabel

Here's the image for that..

答案 4 :(得分:0)

我很好奇,您是否可以控制所显示的文字?如果是这样,你应该把它放在一个UIWebView中并在那里抛出一些链接,以“正确的方式”。

答案 5 :(得分:0)

步骤1.创建UITextview的子类并覆盖 canBecomeFirstResponder 功能

KDTextView.h代码:

@interface KDTextView : UITextView

@end

KDTextView.m代码:

#import "KDTextView.h"

// Textview to disable the selection options

@implementation KDTextView

- (BOOL)canBecomeFirstResponder {
    return NO;
}

@end

步骤2.使用子类KDTextView

创建Textview
KDTextView*_textView = [[KDTextView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    [_textView setScrollEnabled:false];
    [_textView setEditable:false];
    _textView.delegate = self;
    [_textView setDataDetectorTypes:UIDataDetectorTypeAll];
    _textView.selectable = YES;
    _textView.delaysContentTouches = NO;
    _textView.userInteractionEnabled = YES;
    [self.view addSubview:_textView];

第3步:实施委托方法

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
    return true;
}

答案 6 :(得分:0)

Swift 4.2 Xcode 10.1

func setupContactUsTextView() {
        let text = NSMutableAttributedString(string: "Love your App, but need more help? Text, Call (123) 456-1234 or email ")
        if let font = UIFont(name: "Calibri", size: 17) {
            text.addAttribute(NSAttributedStringKey.font,
                              value: font,
                              range: NSRange(location: 0, length: text.length))
        } else {
            text.addAttribute(NSAttributedStringKey.font,
                              value: UIFont.systemFont(ofSize: 17),
                              range: NSRange(location: 0, length: text.length))
        }
        text.addAttribute(NSAttributedStringKey.foregroundColor,
                          value: UIColor.init(red: 112/255, green: 112/255, blue: 112/255, alpha: 1.0),
                          range: NSRange(location: 0, length: text.length))
        text.addAttribute(NSAttributedStringKey.link, value: "tel://", range: NSRange(location: 49, length: 15))
        let interactableText = NSMutableAttributedString(string: "contact@abc.com")
        if let font = UIFont(name: "Calibri", size: 17) {
            interactableText.addAttribute(NSAttributedStringKey.font,
                                          value: font,
                                          range: NSRange(location: 0, length: interactableText.length))
        } else {
            interactableText.addAttribute(NSAttributedStringKey.font,
                                          value: UIFont.systemFont(ofSize: 17),
                                          range: NSRange(location: 0, length: interactableText.length))
        }
        interactableText.addAttribute(NSAttributedStringKey.link,
                                      value: "contact@abc.com",
                                      range: NSRange(location: 0, length: interactableText.length))
        interactableText.addAttribute(NSAttributedStringKey.underlineStyle,
                                      value: NSUnderlineStyle.styleSingle.rawValue,
                                      range: NSRange(location: 0, length: interactableText.length))
        text.append(interactableText)
        videoDescTextView.attributedText = text
        videoDescTextView.textAlignment = .center
        videoDescTextView.isEditable = false
        videoDescTextView.isSelectable = true
        videoDescTextView.delegate = self
    }

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        if (characterRange.location > 48 && characterRange.location < 65){
            print("open phone")
        }else{
            print("open gmail")
        }
        return false
    }

步骤- 1.将委托设置为您的文本字段,不要忘记实现UITextViewDelegate 2.采取textView出口-@IBOutlet弱var videoDescTextView:UITextView! 3.添加上述两个功能。 此功能显示如何检测电话号码,来自textView的电子邮件,如何在电子邮件ID上加下划线,如何为文本赋予自定义颜色,自定义字体,在点击电话或电子邮件时如何调用功能等。

希望这可以帮助某人节省宝贵的时间。快乐编码:)