Получить IndexPath для - UITextView должен взаимодействовать с URL в indexPath - PullRequest
0 голосов
/ 04 апреля 2019

У меня есть представление коллекции. Внутри будет отображаться имя пользователя вместе с тем, если он зарегистрировался в месте и у друзей, которые с ним. Я использую имя пользователя в качестве TextView, и я назначаю URL-адреса для 2 типов текста (друзья и checkIn). Работает как надо только с одной проблемой.

Я не могу найти способ получить IndexPath, когда пользователь нажимает на ссылку. Он отправит ссылку и вызовет функцию, но я не могу получить indexPath. Я посмотрел везде, но нет документации об этом. Всегда в долгу за небольшую помощь, потому что я много боролся с этим.

Эта функция заставляет имя пользователя отображать 2 ссылки:

  //GET THE INDEX PATH FOR ASSIGNMENT TO THE LINKS ??
    func assignNameFriendsAndCheckIn(name: String, checkIn: String, friends: String, cellName: UITextView) {

        let nameSurname = name
        let checkIn = checkIn
        var string = name
        let friendsString = friends

        string = "\(nameSurname)\(checkIn)\(friendsString)"

        let attributedString = NSMutableAttributedString(string: string)

        attributedString.addAttribute(NSAttributedString.Key.font, value: UIFont.boldSystemFont(ofSize: 14), range: (string as NSString).range(of: nameSurname))

        attributedString.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 11), range: (string as NSString).range(of: checkIn))
        attributedString.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 11), range: (string as NSString).range(of: friendsString))

        attributedString.addAttribute(NSAttributedString.Key.link, value: "checkIn", range: (string as NSString).range(of: checkIn))
        cellName.linkTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.black, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 11)]
        attributedString.addAttribute(NSAttributedString.Key.link, value: "friends", range: (string as NSString).range(of: friendsString))
        cellName.linkTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.black, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 11)]

        cellName.attributedText = attributedString
    }

А вот как я ловлю ссылки:

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {

    if URL.absoluteString == "checkIn" {
        print("Check In")
        return true
    } else if URL.absoluteString == "friends" {
        print("Friends")
        return true
    } else {
        print("No Urls set")
        return false
    }

}

1 Ответ

0 голосов
/ 05 апреля 2019

Основываясь на предложении, которое Ларме дал мне, я придумал это, и оно работает.

В didSelectRow я назначаю жест касания, а затем создаю NSAttributedString со ссылками. Во второй части я извлекаю точку жеста в collectionView и получаю indexPath. Теперь действия будут назначены. Поскольку первый щелчок будет по строке, а не по метке, indexPath будет назначен с задержкой. Так что я задерживаю назначение с DispatchQueue:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as! CollectionCell
    cell.nameSurname.delegate = self

    ................................................

    cell.nameSurname.isUserInteractionEnabled = true
    cell.nameSurname.tag = (indexPath.section * 100) + indexPath.item
    let tapName : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapName))
    cell.nameSurname.addGestureRecognizer(tapName)
    tapName.delegate = self

    assignNameLocationAndCheckIn(name: nameSurname, checkIn: checkIn, city: city, date: date, friends: friendsString, cellName: cell.nameSurname, postID: cell.postID)
}

Это функция для вычисления indexPath (urlIndexPath является просто переменной):

@objc func didTapName(sender: UITapGestureRecognizer) {
        let pointInCollectionView = sender.location(in: collectionView)
        let indexPath = collectionView?.indexPathForItem(at: pointInCollectionView)
        urlIndexPath = indexPath!.item
        print("Name was tapped: \(indexPath!.item) : \(posts[(indexPath?.row)!].postID!)")
    }

И, наконец, я использую indexPath:

//MARK: 
    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {

        if URL.absoluteString == "checkIn" {
            print("Check In")
            checkInText()
            return true
        } else if URL.absoluteString == "friends" {
            print("Friends")
            tagFriends()
            return true
        } else {
            print("No Urls set")
            return false
        }

    }

    //MARK: 
    func checkInText() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            print("Send to: \(self.urlIndexPath)")
        }

    }

    //MARK: 
    func tagFriends() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            print("Send to Friends: \(self.urlIndexPath)")
        }

    }
...