在iOS中结合Peek和Pop与Popover

时间:2019-02-18 11:59:14

标签: ios storyboard

是否可以在iOS中将窥视和流行音乐与弹出框结合在一起?

我想在支持3D Touch的iPhone上同时使用peek and pop,同时在iPad上使用弹出窗口。

当我尝试将其合并到情节提要中时,出现错误“无法编译连接”。

enter image description here

1 个答案:

答案 0 :(得分:1)

我自己找到了答案。

问题是PopOver的锚点指向动态创建的原型单元,因此系统不确定哪个单元是锚。

因此,解决方案如下:

  1. 将弹出菜单的定位点设置为表格视图
  2. 因为需要在代码中执行此操作,因此从情节提要中删除了监视和弹出功能。
  3. 转到您的UITableViewDataSource(在我的情况下是视图控制器),然后使用单元格作为源视图将以下内容添加到您的cellForRowAt()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "myCellIdentifier", for: indexPath) as! MyTableViewCell
    let item = items[indexPath.row]
    // Pass the item here...
    registerForPreviewing(with: self, sourceView: cell) // <== Add this
    return cell
}
  1. 之后,您必须像这样遵守协议UIViewControllerPreviewingDelegate
extension ListeningVC: UIViewControllerPreviewingDelegate {
    func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
        guard let indexPath = tableView.indexPathForRow(at: location) else {
            return nil
        }
        // get the item you want to pass using the index path
        let item = items[indexPath.row]
        // get the destination view controller
        let destination = UIStoryboard(name: "...", bundle: nil).instantiateInitialViewController()
        // Pass the item here...
        return destination // return the destination view controller
    }

    func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
        // either present the view controller or add it to your navigation controller here
        present(viewControllerToCommit, animated: true)
    }
}
  1. 如果需要,可以将锚点(源视图)稍微居中:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    switch segue.identifier {
    case "mySegueIdentifier":
        guard let cell = sender as? MyTableViewCell else { return }
        guard let indexPath = tableView.indexPath(for: cell) else { return }
        let item = items[indexPath.row]
        let destination = segue.destination
        // Pass the item here...
        if let popOver = segue.destination.popoverPresentationController {
            // set the cell as source view
            let origin = CGPoint(x: 100, y: cell.frame.origin.y)
            let size = CGSize(width: 200, height: cell.frame.height)
            popOver.sourceView = tableView
            popOver.sourceRect = CGRect(origin: origin, size: size)
        }
    default:
        break
    }
}
  1. 对此感到高兴,并对这个答案给予支持。 :)