我是swift的初学者。 我想从tableviewcell调用collectionview。
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let window = UIWindow(frame: UIScreen.mainScreen().bounds)
let layout = UICollectionViewLayout()
let detailColorView = ColorCollectionView(collectionViewLayout: layout)
switch indexPath.row {
case 0:
detailColorView.bkColor = UIColor.redColor()
case 1:
detailColorView.bkColor = UIColor.greenColor()
case 2:
detailColorView.bkColor = UIColor.blueColor()
default:
detailColorView.bkColor = UIColor.blackColor()
}
window.rootViewController = UINavigationController(rootViewController: detailColorView)
self.navigationController?.pushViewController(detailColorView, animated: true)
}
这是以编程方式创建的collectionviewController。
import UIKit
private let reuseIdentifier = "Cell"
class ColorCollectionView: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var bkColor: UIColor!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Select a color"
if bkColor != nil{
collectionView?.backgroundColor = bkColor
}else{
collectionView?.backgroundColor = UIColor.blackColor()
}
self.collectionView?.registerClass(ColorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ColorCell
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: view.frame.width, height: 100)
}
}
class ColorCell: UICollectionViewCell{
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupViews()
{
backgroundColor = UIColor.whiteColor()
}
}
但是在运行之后,单击tableviewcell时,会出现collectionview,但是自定义单元格没有出现任何错误或问题。
我想通过快速编程经验来解决问题。 感谢
答案 0 :(得分:0)
代码看起来不错,但我认为您仍然需要在课程顶部添加UICollectionViewDataSource
。
class ColorCollectionView: UICollectionViewController, UICollectionViewDelegateFlowLayout, HERE {
以后添加:
self.collectionView.dataSource = self;
进入viewDidLoad()