从UITableViewCell类中获取UITextView中的hashtag后尝试进行segue

问题描述 投票:1回答:1

使用URL.scheme我在UITextView类中的UITableViewCell中获取了标签,但我有两个问题。

首先,如何从细胞类中脱离出来。我没有perform segue功能。只在UITableView类中找到。

其次,如何将标签名称或提及名称发送到新的UIViewController。我可以使用委托方法或通过执行segue发送它。但是,我将如何从细胞类中脱离出来。

下一个代码是在UITableViewCell类中编写的

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

    let path = URL.absoluteString
    switch URL.scheme! {
    case "hash" :
        let hash = path.removingPercentEncoding?.components(separatedBy: ":").last
        print(hash!) // ---> Retriving tapped on hash name correctly

    case "mention" :
        let mention = path.removingPercentEncoding?.components(separatedBy: ":").last
        print(mention!) // ---> Retriving tapped on mention name correctly
    default:
        print("Just a regular link \(path.removingPercentEncoding!)")
    }
    return true
}
swift uitableview delegates uitextview segue
1个回答
0
投票

有几种不同的方法可以做到这一点,但我可能会使用自定义委托协议。在单元文件中定义协议,如下所示:

protocol MyTableViewCellDelegate: class {
    func myTableViewCell(_ cell: MyTableViewCell, shouldSelectHashTag tag: String)
}

将属性添加到表视图单元类:

class MyTableViewCell: UITableViewCell {
    // make sure the property is `weak`
    weak var delegate: MyTableViewCellDelegate?
}

我假设您的表视图数据源也是您想要执行segue的视图控制器。使此视图控制器符合新协议:

extension MyViewController: MyTableViewCellDelegate {
    func myTableViewCell(_ cell: MyTableViewCell, shouldSelectHashTag tag: String) {
        performSegue(withIdentifier: "MyHashTagSegue", sender: tag)
    }
}

将视图控制器指定为cellForRowAtIndexPath数据源方法中表视图单元的委托:

let cell: MyTableViewCell = <dequeue the cell>
cell.delegate = self

最后,不要忘记从表视图单元格中调用委托方法:

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
    let tag = <get the hash tag> 
    delegate?.myTableViewCell(self, shouldSelectHashTag: tag)
}
© www.soinside.com 2019 - 2024. All rights reserved.