繁体   English   中英

如何在Swift中为视图集合中的每个单元格添加弹出窗口

[英]How to add popovers for every cell in view collection in Swift

我正在用文字写一个应用程序(游戏类型)。 所以,我有WordsVC和CollectionView (每个单元格是一个单词)。 当长按单词(单元格)时,我想在单元格旁边显示带有翻译的弹出窗口。

但是我无法将segue添加到单元格中(Xcode给我一个错误,有点“无法编译”)。 因此,我正在从CollectionView到TraslationVC(popover)。 那是个问题,因为弹出框会在视图集合的左上角弹出(我需要在轻击的单元格旁边)。

我无法通过搜索找到满意的答案。 我该怎么做呢?

这是一些代码:

在WordsVC中准备segue:

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // for another segue
    if segue.identifier == "fromWordsToWin" {
        if let wvc = sender as? WordsViewController {
            if let winVC = segue.destination as? WinningViewController {
                winVC.completedLevel = wvc.currentLevel
                winVC.levelsCount = wvc.dataSource.count()
                winVC.resultTime = wvc.result
            }
        }
    }
    // here
    if segue.identifier == "translationSegue" {
        if let cell = sender as? WordCell {
            if let tvc = segue.destination as? TranslationViewController {
                tvc.text = cell.myLabel.text ?? "empty cell"
                if let ppc = tvc.popoverPresentationController {
                    ppc.delegate = self
                }

            }
        }
    }
}

在WordsVC中设置非模式样式:

 func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
    return UIModalPresentationStyle.none
}

序列化(来自WordsVC):

@objc func longTap(_ sender: UIGestureRecognizer) {
    print("long tap happend")
    if let cell = sender.view as? WordCell {
        performSegue(withIdentifier: "translationSegue", sender: cell)
    }

并在TranslatingVC中设置弹出窗口的大小:

 override var preferredContentSize: CGSize {
    get {
        if textView != nil && presentingViewController != nil {
            return textView.sizeThatFits(presentingViewController!.view.bounds.size)
        } else {
            return super.preferredContentSize
        }
    }
    set { super.preferredContentSize = newValue}
}

这个怎么做?

建议我使用popoverViewController.sourceView。 因此,它运作良好! 我还添加了一些有关弹出窗口确切位置的设置。 我在prepareForSegue下面的代码(代码的最后2行):

 if segue.identifier == "translationSegue" {
        if let cell = sender as? WordCell {
            if let tvc = segue.destination as? TranslationViewController {
                tvc.text = cell.myLabel.text ?? "empty cell"
                if let ppc = tvc.popoverPresentationController {
                    ppc.delegate = self
                    ppc.sourceView = cell
                    ppc.sourceRect = CGRect(x: cell.bounds.minX + cell.bounds.width / 5, y: cell.bounds.minY, width: 50, height: 50 )
                }

            }
        }
    }

屏幕截图,现在的样子

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM