簡體   English   中英

如何讓 UITextView 檢測網站、郵件和電話號碼的鏈接

[英]How to make UITextView detect links for website, mail and phone number

我有一個UITextView object。UIView里面的文字有電話號碼,郵件鏈接,網址鏈接。 我想將它們顯示為具有以下功能的鏈接。

當有人點擊 URL - Safari 應該打開網站。 當有人點擊 email 鏈接時 - 郵件應在字段中打開我的地址當有人點擊電話號碼時 - 電話應用程序應撥打該號碼

以前有沒有人這樣做過或知道如何處理?

謝謝,阿傑

如果您使用的是 OS3.0

你可以像下面這樣

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

關於檢測電子郵件地址的注意事項:必須安裝郵件應用程序(它不在 iOS 模擬器上),電子郵件鏈接才能打開郵件撰寫屏幕。

斯威夫特 3.0 +

從 swift 3.0 開始,如果要以編程方式執行,請使用以下代碼。

textview.isEditable = false
textview.dataDetectorTypes = .all

或者如果你有一個故事板

在此處輸入圖片說明

雖然問題是超級老。 如果有人面臨同樣的問題,

它也可以用作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 和 Call App

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 的 Delegate 方法

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

這是圖片..

Step 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];

第三步:實現委托方法

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

斯威夫特 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 weak var videoDescTextView: UITextView! 3. 添加上面給出的這兩個函數。 該函數展示了如何檢測電話號碼、textView 中的電子郵件、如何為電子郵件 ID 加下划線、如何為文本自定義顏色、自定義字體、如何在點擊電話或電子郵件時調用函數等。

希望這能幫助某人節省寶貴的時間。 快樂編碼:)

如果您想自動檢測鏈接,email 等請確保“ isSelectable ”設置為 true。

textview.isSelectable = true
textview.editable = false
textview.dataDetectorTypes = .all

我很好奇,你能控制顯示的文字嗎? 如果是這樣,您可能應該將其粘貼在 UIWebView 中並在其中放置一些鏈接以“以正確的方式”執行此操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM