【发布时间】:2014-12-09 15:46:06
【问题描述】:
我正在尝试在用户选择时添加一个集合视图单元格。他在一个单独的视图控制器中执行此操作,并在其中给出名称并保存它。但是当它返回到初始视图控制器时,新单元格不会被添加到集合视图中。
这是我的 2 个视图控制器的代码:
import UIKit
class FlashViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet var collectionView: UICollectionView!
var decks: [Deck] = []
override func viewDidLoad() {
super.viewDidLoad()
// Move on ...
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 75, left: 20, bottom: 10, right: 20)
layout.itemSize = CGSize(width: 150, height: 200)
collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
self.collectionView.dataSource = self
self.collectionView.delegate = self
collectionView.registerClass(DeckCollectionViewCell.self, forCellWithReuseIdentifier: "DeckCollectionViewCell")
collectionView.backgroundColor = UIColor.whiteColor()
self.view.addSubview(collectionView!)
var deck1 = Deck()
deck1.name = "SAT is the bomb"
self.decks.append(deck1)
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.decks.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("DeckCollectionViewCell", forIndexPath: indexPath) as DeckCollectionViewCell
cell.backgroundColor = UIColor.blackColor()
cell.textLabel?.text = "\(indexPath.section):\(indexPath.row)"
cell.imageView?.image = UIImage(named: "circle")
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var nextViewController = segue.destinationViewController as NewDeckViewController
nextViewController.deckCollection = self
}
}
下一个视图控制器:
import UIKit
class NewDeckViewController : UIViewController
{
@IBOutlet weak var deckNameTextField: UITextField!
var deckCollection = FlashViewController()
override func viewDidLoad() {
super.viewDidLoad()
// Move on...
}
@IBAction func cancelTapped(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func createTapped(sender: AnyObject) {
var newDeck = Deck()
newDeck.name = self.deckNameTextField.text
self.deckCollection.decks.append(newDeck)
self.dismissViewControllerAnimated(true, completion: nil)
}
}
【问题讨论】:
-
大部分代码看起来不错...尝试在
viewWillAppearofcollectionView中重新加载集合视图。
标签: ios swift uicollectionview