【问题标题】:Push viewController from CollectionView cell programmatically not working - swift以编程方式从 CollectionView 单元推送 viewController 不起作用 - swift
【发布时间】:2018-07-23 09:04:26
【问题描述】:

我是一个新的iOS编程。现在我正在创建一个示例应用程序,不使用storyboard,我为滚动方向为垂直的主类实现了UICollectionView。一个特定的单元格我添加了另一个UICollectionView 用于水平方向。问题是cell 哪个水平滚动方向没有推送到我单击它的另一个视图控制器。

这是我在AppDelegate 中设置的rootViewController

window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
let navigation = UINavigationController(rootViewController: CategoryController())
window?.rootViewController = navigation

这是CategoryController,我实现了tableView

tableView.register(TableCell.self, forCellReuseIdentifier: cellId)

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 5
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)

    return cell
}

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 120
}

对于tableView,当我想要导航到特定控制器时,当我单击特定单元格时工作正常

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    print(indexPath.item)
    let view = DetailEachCellController()
    navigationController?.pushViewController(view, animated: true)
}

问题是在DetailEachCellController 我使用UICollectionView 列出一些数据,当我点击特定单元格时不会导航到新控制器

这里是DetailEachCellControllerUIViewController

var collectionDetailView: UICollectionView!
collectionDetailView.register(DetailContactCell.self, forCellWithReuseIdentifier: cellIdContact)
collectionDetailView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellIdContent)

func setupCollectionView() {
    collectionDetailView.topAnchor.constraint(equalTo: detailContent.topAnchor).isActive = true
    collectionDetailView.widthAnchor.constraint(equalTo: detailContent.widthAnchor).isActive = true
    collectionDetailView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
    collectionDetailView.backgroundColor = .white 
}

func callAction() {
    print("pushing view")
    let view = UIViewController()
    self.navigationController?.pushViewController(view, animated: true)
}

这里是UICollectionViewFlowLayout的代表

extension DetailEachCellController : UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 2
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.item == 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdContact, for: indexPath)

            return cell
        }
        else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdContent, for: indexPath)
            cell.backgroundColor = .blue
            return cell
        }
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if indexPath.item == 1 {
          return CGSize(width: view.frame.width, height: 250)
        }
        return CGSize(width: view.frame.width, height: 120)
    }
}

这里是DetailContactCell,我添加了一些按钮供用户点击和更多到下一个视图,但它没有移动但调用了函数。

class DetailContactCell: UICollectionViewCell {

var eachCellController: DetailEachCellController?

lazy var callButton: UIButton = {

    let button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false
    button.layer.shadowOpacity = 0.25
    button.backgroundColor = .white
    button.setTitle("CALL", for: .normal)
    button.layer.cornerRadius = 10
    button.layer.shadowOffset = CGSize(width: 0, height: 10)
    button.layer.shadowRadius = 10
    return button
}()
lazy var bookButton: UIButton = {

    let button = UIButton()
    button.translatesAutoresizingMaskIntoConstraints = false
    button.layer.shadowOpacity = 0.25
    button.backgroundColor = .white
    button.layer.cornerRadius = 10
    button.layer.shadowOffset = CGSize(width: 0, height: 10)
    button.layer.shadowRadius = 10
    return button
}()
override init(frame: CGRect) {
    super.init(frame: frame)
    addSubview(callButton)
    addSubview(bookButton)
    callButton.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
    callButton.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 15).isActive = true
    callButton.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 1/2.5).isActive = true
    callButton.heightAnchor.constraint(equalToConstant: 60).isActive = true

    bookButton.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
    bookButton.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -15).isActive = true
    bookButton.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 1/2.5).isActive = true
    bookButton.heightAnchor.constraint(equalToConstant: 60).isActive = true

    self.actionButton()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func actionButton() {
    callButton.addTarget(self, action: #selector(callBtn), for: .touchUpInside)
}

@objc func callBtn() {
    print("calling")
    eachCellController = DetailEachCellController()
    eachCellController?.callAction()
}

}

【问题讨论】:

    标签: ios swift uinavigationcontroller uicollectionviewflowlayout


    【解决方案1】:
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if indexPath.item == 0 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdContact, for: indexPath) as! DetailContactCell
            // Here is line add to `UICollectionViewFlowLayout`
            cell.eachCellController = self
    
            return cell
        }else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdContent, for: indexPath)
            cell.backgroundColor = .blue
            return cell
        }
    
    }
    

    【讨论】:

      【解决方案2】:

      因为这个

      // eachCellController = DetailEachCellController() // 注释它

      是另一个 VC,而不是提出的一个

      eachCellController?.callAction()
      

      您需要将自己发送到cellForItemAt

      cell.eachCellController = self
      

      //

      @objc func callBtn() {
         print("calling")
         eachCellController?.callAction()
      }
      

      【讨论】:

      • 将处理UICollectionViewUIViewController 的强实例传递给UICollectionViewCell 对象并不好。这很容易受到保留循环的影响。委托模式和处理程序适合这种情况。
      • @Malloc 他可以声明它是弱的
      【解决方案3】:

      您不能从UICollectionViewCell 类内部将新的视图控制器推送到导航控制器堆栈。

      这样做的方法是告诉DetailEachCellController(通过委托方法或回调处理程序)按钮被点击,然后ONLY FROM DetailEachCellController你可以推送视图控制器.

      这是similar thread

      【讨论】:

      • 感谢您的精彩解释。我会努力解决的
      【解决方案4】:

      UIViewController 的强对象传递给单元格并不方便。您可以创建保留周期,并且您的视图控制器将永远不会像内存一样被释放,因此将来可能会导致内存问题

      要解决此问题,您可能有以下选项

      1. 使用委托
      2. 使用闭包
      3. 使用addTarget 在视图控制器本身中实现按钮操作

      由于关闭选项很简单,我给你一个例子来实现它。

      在您的集合视图单元格中添加以下属性

      var callBtnTapped : (() -> ())?
      

      现在在 .

      @objc func callBtn() {
          print("calling") 
           // Check that target has implemented closure ? 
           if let clouser = self.callBtnTapped {
                  clouser(screenShotID)
            }
      }
      

      在您的视图控制器cellForItem 中将主体添加到闭包

           cell.callBtnTapped = {[weak self]  in
              guard let strongSelf = self   else  {return}
              strongSelf. callAction()
              // It will be called when button tapped 
          }
      

      希望对你有帮助

      【讨论】:

      • 这也是我正在寻找的,对我很有帮助。
      • @SamboPisal 很高兴它对你有帮助
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 2017-08-20
      • 2021-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多