我正在尝试编写一个类来显示一个collectionView。 我试图将collectionView作为子视图添加到调用类的UIView时遇到了麻烦。 这可能吗? 非常感谢任何见解。
ViewController:
import UIKit
class ViewController: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
let editMenu = collection(view: view, xPos: 0, yPos: 0, width: view.frame.width, height: view.frame.height)
}
}
和集合视图Class:
import UIKit
class collection: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
var collectionView: UICollectionView?
let cellIdentifier = "CellIdentifier"
var myView = UIView()
var xPos, yPos, width, height: CGFloat
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(view: UIView, xPos: CGFloat, yPos: CGFloat, width: CGFloat, height: CGFloat) {
self.myView = view
self.xPos = xPos
self.yPos = yPos
self.width = width
self.height = height
super.init(nibName: nil, bundle: nil)
configureCollection()
}
func configureCollection()
{
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 00, left: 10, bottom: 10, right: 10)
layout.itemSize = CGSize(width: 100, height: 80)
let frame = CGRectMake(xPos, yPos, width, height)
collectionView = UICollectionView(frame: frame, collectionViewLayout: layout)
collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: cellIdentifier)
collectionView!.backgroundColor = UIColor.redColor()
collectionView!.dataSource = self
collectionView!.delegate = self
myView.addSubview(collectionView!) //<- EXC_BAD_ACCESS
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 4
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 2
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! UICollectionViewCell
var textLabel = UILabel(frame: CGRectMake(0, 0, cell.frame.size.width, cell.frame.size.height))
textLabel.textAlignment = NSTextAlignment.Center
textLabel.textColor = UIColor.darkTextColor()
textLabel.text = "Cell \(indexPath.row)"
cell.contentView.addSubview(textLabel)
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
NSLog("selected \(indexPath.row)")
}
}