在 UICollectionViewController 上显示操作表警报



我的项目中有名为DiaryCell的自定义CollectionViewCell。我使用该类配置我的单元格。每个单元格都有此菜单按钮,单击它时UICollectionviewcontroller我希望显示操作表,但它给了我以下错误。

'NSInvalidArgumentException', reason: 'UICollectionView must be initialized with a non-nil layout parameter'

下面是在单元格中按下菜单按钮时处理该操作的代码。此操作在 UICollectionViewController 中处理。总而言之,我的点击手势是在customCell中定义的,当点击时,它会将代码重定向到控制器以处理操作。

    func menuButtonPressed(_ gesture: UITapGestureRecognizer) {

    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
    let editAction = UIAlertAction(title: "Edit", style: .default) { (action) in
    }
    let deleteAction = UIAlertAction(title: "Delete", style: .destructive) { (action) in
    }
    let alert = UIAlertController(title: "Pick Your Adventure 😜", message: "You have the following options", preferredStyle: .actionSheet)
    alert.addAction(cancelAction)
    alert.addAction(editAction)
    alert.addAction(deleteAction)
    present(alert, animated: true, completion: nil)
}

我相信这与视图图层有关。由于单元格是在UICollectionview内敲击的,它不知道如何以及在哪里显示操作表。我可能是错的。感谢您阅读我的问题。

编辑:负责将操作重定向到控制器的代码。

    var homeCollection = HomeCollectionViewController()
    let menuImageView: UIImageView = {
    let imageView = UIImageView()
    imageView.image = #imageLiteral(resourceName: "menu_image")
    imageView.contentMode = .scaleAspectFit
    imageView.clipsToBounds = true
    imageView.isUserInteractionEnabled = true
    imageView.translatesAutoresizingMaskIntoConstraints = false
    return imageView
}()
    func setUpMenuItemGesture() {
    let tapGesture = UITapGestureRecognizer(target: self.homeCollection, action: #selector(self.homeCollection.menuButtonPressed(_:)))
    tapGesture.numberOfTapsRequired = 1
    tapGesture.delegate = homeCollection
    menuImageView.addGestureRecognizer(tapGesture)
}

我的UICollectionViewController中的布局代码:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width = collectionView.frame.size.width
    return CGSize(width: width, height: width + (width*(0.15)))
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0
}

我的猜测是问题出在这条线上:

var homeCollection = HomeCollectionViewController()

这会导致创建一个全新的、独立的 HomeCollectionViewController。它从未正确初始化,因此无效;更重要的是,它不是你想要的HomeCollectionViewController。您需要引用已在使用的现有 HomeCollectionViewController,而不是新的和不同的 HomeCollectionViewController。

最新更新