【问题标题】:How to perform navigation from UIView to ViewController如何执行从 UIView 到 ViewController 的导航
【发布时间】:2019-03-21 18:18:44
【问题描述】:

在我的主屏幕上有多个 UICollectionView 部分,所以我为每个部分(xib)使用了单独的 - 单独的视图(UICollectionViews)现在我必须执行导航(didSelectItemAt)我无法即使没有错误也执行它

我使用下面的导航代码(didSelectItemAt

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
          let vc = UIStoryboard.init(name: "ProductListing", bundle: Bundle.main).instantiateViewController(withIdentifier: "ProductListingViewController") as? ProductListingViewController
    (superview?.next as? ProductListingViewController)?.navigationController?.pushViewController(vc!, animated: true)}

【问题讨论】:

  • 永远不要(superview?.next as? ProductListingViewController)?。使用委托协议、闭包或通知(取决于您的用例)

标签: ios swift uiview uinavigationcontroller


【解决方案1】:

您可以为此使用callbacks

在您的collectionView View 中添加此回调:

var didSelectCallback: (() -> Void)?

然后在collectionViewdidSelectItem委托方法中写下:

if let callBack = didSelectCallback {
   callBack()
}

然后在控制器中添加此collectionView View 时添加此回调:

yourView.didSelectCallback = { [weak self] in 
   guard let weakSelf = self else {return}
   let vc = UIStoryboard.init(name: "ProductListing", bundle: Bundle.main).instantiateViewController(withIdentifier: "ProductListingViewController") as? ProductListingViewController
   weakSelf.navigationController?.pushViewController(vc!, animated: true)}
}

【讨论】:

    【解决方案2】:

    更好的方法是从视图发送回调到 ViewController 并从它执行导航,如下所示:

    class View: UIView {
         var didTapSomething: () -> Void
    }
    

    在 ViewController 中:

    class ViewController: UIViewController {
        @IBOutlet var view: View!
    
        override func viewDidload() {
           super.viewDidLoad()
           view.didTapSomething = {
              //perform navigation
           }
        }
    }
    

    【讨论】:

      【解决方案3】:

      试试这个:

      let storyboard = UIStoryboard(name: "ProductListing", bundle: nil)
      let productListingVC = storyboard.instantiateViewController(withIdentifier: "ProductListingViewController")
      self.present(productListingVC, animated: true, completion: nil)
      

      【讨论】:

      • 我已经使用这个方法给出了一个错误 self.present not a member or UIView Class (Value of type 'PopularProducts' has no member 'present')
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-16
      • 2015-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多