【问题标题】:Trying to segue after tapping hashtag in UITextView from a UITableViewCell class从 UITableViewCell 类中点击 UITextView 中的标签后尝试继续
【发布时间】:2017-12-18 23:00:12
【问题描述】:

使用URL.scheme,我在UITextViewUITableViewCell 类中获得了主题标签,但我有两个问题。

首先如何从单元格类中分离出来。我没有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】:

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

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

    向表格视图单元格类添加属性:

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

    我假设您的表视图数据源也是您要从中执行转场的视图控制器。使这个视图控制器符合新协议:

    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)
    }
    

    【讨论】:

    • 很好的答案,我认为它会起作用。但是我的 ViewController 与我试图继续的故事板不同。你觉得我怎么能解决这个问题<...>
    • 您可以使用情节提要参考。这是另一个可以像视图控制器一样拖入情节提要的对象,并且可以将 segue 附加到它。
    • 是的,这就是我所做的,我将 ViewController 实例化到我选择的情节提要中并且它起作用了。谢谢:))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    相关资源
    最近更新 更多