我有一个UICollectionView
,显示图像的缩略图。当我点击这个单元格(缩略图)时,我使用下面的功能推送另一个UIViewController
,然后可以下载并查看缩略图的放大图像。我在每个细胞内都有一个UIButton
。我想提出另一个viewController
作为自定义弹出窗口,我希望显示有关图像的更多细节,例如文件名,日期等...当设置action
连接到自定义UICollectionViewCell
类,并在IBAction
函数内方法,我无法'呈现'这个自定义UIViewController
。 Xcode
只是不承认'现在'。有人可以建议吗?
class CollectionViewFolder: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate ,UICollectionViewDelegateFlowLayout{
...
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){
}
...
}
自定义:
class CollectionViewFolderCell: UICollectionViewCell {
@IBAction func moreInfoBtn(_ sender: Any) {
// DOES NOT RECOGNIZE 'present' - TO PRESENT ANOTHER UIVIEWCONTROLLER
}
}
在CollectionViewFolderCell.swift
中创建协议
protocol CollectionViewFolderCellDelegate {
func collectionViewFolderCellDidPressButton()
}
在CollectionViewFolderCell
内部声明一个代表:
var delegate: CollectionViewFolderCellDelegate?
在你的按钮动作内添加:
@IBAction func moreInfoBtn(_ sender: Any) {
delegate?.collectionViewFolderCellDidPressButton()
}
在你的cellForItemAtIndexPath方法中添加cell.delegate = self
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewFolderCell
cell.delegate = self
return cell
}
同样在您的View Controller中,您需要符合您的CollectionViewFolderCellDelegate
extension CollectionViewFolder: CollectionViewFolderCellDelegate {
// here you can present your desired view controller
}
present(_:animated:completion:)
是一个UIViewController
。为了能够显示(呈现,推送,弹出等)另一个UIViewController
,你必须是一个UIViewController(或者在推送等情况下的特定一个)。所以CollectionViewFolderCell
不能展示你的新UIViewController
。
然后你需要告诉UIViewController
(在你的情况下CollectionViewFolder
)你的细胞(在你的情况下CollectionViewFolderCell
通过它的UICollectionView
)这样做。对此,您可以使用委托模式或闭包。
带闭包的快速示例代码:
添加属性到CollectionViewFolderCell
:
var onMoreInfoTap: ((ParamTypeOrClass1, ParamTypeOrClass2, etc) -> Void)?
然后修改你的方法:
@IBAction func moreInfoBtn(_ sender: Any) {
//Compute all your params, let's name them param1, param2, etc.
self.onMoreInfoTap?(param1, param2, etc.
}
在func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
:
cell.onMoreInfoTap = { [weak self] (param1Name, param2Name, etc) in
let viewController = //Create your target UIViewController
//Set its customs var according to Param1Name, Param2Name, etc.
self?.present(viewController, animated: true, completion:nil)
}