从CollectionView单元格以编程方式推送viewController不起作用 - Swift

3
我是一名新的iOS程序员。现在我正在创建一个样例应用,不使用storyboard,而是实现了垂直滚动方向的主类UICollectionView。特定的单元格中,我添加了另一个水平方向的UICollectionView。问题是,单元格中水平方向的滚动不能将我点击的内容推到另一个视图控制器中。
以下是我在AppDelegate中设置的rootViewController
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
let navigation = UINavigationController(rootViewController: CategoryController())
window?.rootViewController = navigation

这里是我实现tableViewCategoryController

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来列出一些数据,但是当我点击特定的单元格时,它不会导航到新的控制器。
在这里,DetailEachCellController是一个UIViewController
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()
}

}
4个回答

3

因为这个

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

是另一个视图控制器,而不是当前正在显示的那个

eachCellController?.callAction()

cellForItemAt方法中,你需要发送self。

cell.eachCellController = self

//

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

将处理UICollectionViewUIViewController的强实例传递给UICollectionViewCell对象是不好的。这会导致保留循环漏洞。委托模式和处理程序是为这种情况而设计的。 - Malloc
@Malloc 他可以将其声明为弱引用。 - Shehata Gamal

3
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
您不能从UICollectionViewCell类内部将新视图控制器推入导航控制器堆栈。
正确的方法是通过委托方法或回调处理程序告诉DetailEachCellController按钮被点击了,然后只能从DetailEachCellController中推出视图控制器。
这里有一个类似的讨论

1
感谢您精彩的解释。我会尝试弄清楚它。 - I Love Coding

1
这种将 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 
    }

希望对您有所帮助。

1
这也是我正在寻找的,对我非常有帮助。 - I Love Coding
1
@SamboPisal 很高兴它对你有所帮助。 - Prashant Tukadiya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接