Как определить, была ли нажата ссылка внутри UITextView внутри TabelCell, Swift

Моя цель - регистрировать все ссылки, по которым нажимает пользователь. Ссылки встроены в UITextView внутри ячейки таблицы, и когда пользователь нажимает ссылку, я хочу, чтобы она вызывала функцию, которая печатает URL-адрес.

Я просмотрел похожие вопросы, такие как Как определить, была ли нажата ссылка внутри UITextView, Swift и Как перехватить щелчок по ссылке в UITextView?, где люди предлагали использовать функцию shouldInteractWithURL, но функция никогда не вызывается.

Я думаю, что, возможно, я установил делегата или функцию не в том месте, и было бы здорово, если бы кто-нибудь мог сообщить мне, как это должно быть настроено.

Вот сокращенный код и несколько скриншотов страницы:

class BSPdetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextViewDelegate {


    func textView(textView: UITextView!, shouldInteractWithURL URL: NSURL!, inRange characterRange: NSRange) -> Bool {
        print("Link Selected!")
        return true

    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "detailCell", for: indexPath as IndexPath) as! detailCell
        cell.label?.text = ""


        cell.detailLinks.delegate = self
        cell.detailLinks.isUserInteractionEnabled = true // default: true
        cell.detailLinks.isEditable = false // default: true
        cell.detailLinks.isSelectable = true // default: true
        cell.detailLinks.dataDetectorTypes = [.link]

        cell.detailTextLabel?.font = UIFont.fontAwesome(ofSize: 20)
        cell.detailTextLabel?.text = ""
        cell.detailTextLabel?.numberOfLines = 0;


        cell.detailLinks?.text = "links are here"
        var linkString = NSMutableAttributedString(string: "", attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: 22.0)])
        let video =  String.fontAwesomeIcon(code: "fa-video-camera")! + "  "
        let document = String.fontAwesomeIcon(code: "fa-file-text")! + "\n\n"

        for i in 0..<stratList.count {
            var stratURL = stratList[i].lowercased().replacingOccurrences(of: " ", with: "-")

            var docLink = "http://" + stratURL
            var videoLink = "http://" + stratURL

            //setting the url
            var attributedString = NSMutableAttributedString(string: video, attributes: [NSFontAttributeName: UIFont.fontAwesome(ofSize: 22)])
            attributedString.addAttribute(NSLinkAttributeName, value: docLink, range: NSRange(location: 0, length: 1))
            linkString.append(attributedString as NSAttributedString)

            attributedString = NSMutableAttributedString(string: document, attributes: [NSFontAttributeName: UIFont.fontAwesome(ofSize: 22)])
            attributedString.addAttribute(NSLinkAttributeName, value: videoLink, range: NSRange(location: 0, length: 1))
            linkString.append(attributedString as NSAttributedString)


            cell.label?.text = (cell.label?.text)! + "• " + stratList[i] + "\n\n"


            cell.detailLinks?.attributedText = linkString

            //tried tapgesture but it didn't work when I tapped on the links
            //cell.detailLinks.addGestureRecognizer(UITapGestureRecognizer(target: cell.detailLinks, action: #selector(cell.detailLinks.singleTap(tap:))))

            cell.backgroundColor = contentColors[rowNo]
            cell.label?.textColor = UIColor.black
        }


        return cell
    }
}

class detailCell: UITableViewCell
{

    @IBOutlet weak var detailLinks: UITextView!
    @IBOutlet weak var label: UILabel!

}

введите описание изображения здесь

Результирующая таблица:  введите описание изображения здесь


person haedaldal    schedule 16.06.2018    source источник
comment
UITextViewDelegate методы shouldInteractWithURL должны быть написаны вне cellForRowAt, а не внутри.   -  person Govind Kumawat    schedule 16.06.2018
comment
@GovindKumawat Спасибо! Я пробовал, но функция все еще не вызывается. Есть другие предложения?   -  person haedaldal    schedule 16.06.2018


Ответы (1)


UITextViewDelegate методы shouldInteractWithURL должны быть написаны вне cellForRowAt, а не внутри. Ваша стандартная настройка UITextView должна выглядеть примерно так, не забудьте делегат и dataDetectorTypes.

    cell.detailLinks.delegate = self
    detailLinks.isUserInteractionEnabled = true // default: true
    detailLinks.isEditable = false // default: true
    detailLinks.isSelectable = true // default: true
    detailLinks.dataDetectorTypes = [.link]

UITextViewDelegate метод shouldInteractWithURL:

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
    print("Link Selected!")
    return true
}
person Govind Kumawat    schedule 16.06.2018
comment
Еще раз спасибо! Я пробовал их, но функция до сих пор не вызывается. Я обновил код, чтобы отразить ваши предложения. - person haedaldal; 17.06.2018
comment
@haedaldal проблема здесь в вашем UITextViewDelegate методе shouldInteractWithURL вы используете неправильный метод, у которого отсутствует один параметр, возможно, он использовался в предыдущей быстрой версии. - person Govind Kumawat; 17.06.2018
comment
Это меня действительно спасло. Я, по-видимому, скопировал старую версию функции shouldInteractWithUrl откуда-то еще и не мог заставить ее работать. Наконец-то он заработал! - person Elisabeth Whiteley; 27.07.2020