我是iOS开发的新手。我想在两个具有相同UI的不同视图控制器中创建collectionView。我想只创建一个UICollectionView并在不同的视图控制器上重新使用它,而不是创建单独的collectionViews。我可以遵循的方法是创建UICollectionViewController子类并将其作为childviewcontroller添加到我的viewcontrollers上,但不确定这是否是正确的方法不知道addChildViewcontroller如何工作以及如何在子视图控制器和父视图控制器之间传递数据。如果有人可以提供帮助,那就太棒了。如果有任何示例代码可以获得,请告诉我。
非常感谢任何帮助。
答案 0 :(得分:3)
您可以传递相同的集合视图控制器实例。在viewWillAppear中添加它,并在第一个和第二个类中的viewDidDisappear中删除它。以下是您可以使用的示例代码,
editor.commands.bindKey("Tab", null)
editor.commands.bindKey("Shift-Tab", null)
}
extension UIColor {
class func randomColor() -> UIColor {
let red = CGFloat(arc4random_uniform(255)) / 255.0
let green = CGFloat(arc4random_uniform(255)) / 255.0
let blue = CGFloat(arc4random_uniform(255)) / 255.0
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
答案 1 :(得分:0)
我有一套你可以使用的答案,
我的源代码是ParentViewController和ChildViewController 要声明的viewController相同。
首先创建ParentViewController并添加
然后,UICollectionView在ParentViewController中设置Cell大小。
其次,您在同一个parentViewController中创建UICollectionViewCell, 然后添加你需要标注或按钮的内容。
在ParentViewController类中声明'UICollectionViewDelegate',
Ex:类MyViewController:UIViewController,UICollectionViewDelegate
func numberOfSectionsInCollectionView(collectionView:UICollectionView) - > Int { 返回1 }
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrayvalue.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell
let baseView = cell.viewWithTag(101)
let titleLabel = baseView?.viewWithTag(102) as! UILabel
titleLabel.text = arrayvalue[indexPath.row] as String
return cell
}
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSizeMake(CellSize)
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath)
{
collectionView.deselectItemAtIndexPath(indexPath, animated:true)
let storyBoard = UIStoryboard(name: "storyboardName", bundle: nil)
let name: classname = storyBoard.instantiateViewControllerWithIdentifier("reuseIdentifier") as! AnotherViewController
self.navigationController?.pushViewController(name, animated: true)
}
非常重要的是提供故事板'reuseIdentifier'的价值 在类cellForItemAtIndexPath中给出reuseIdentifier,例如这行
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("reuseIdentifier", forIndexPath: indexPath)
这段代码对我有用......