【发布时间】:2015-10-30 05:21:34
【问题描述】:
我有一个关于 UICollectionView 的相当基本的问题,并将数据传递给多个视图控制器,具体取决于按下的单元格。
在 ViewController.swift - 我拥有在控制器视图中显示单元格的所有代码。如您所见,我有一个小打印线测试,它告诉我哪个单元格(最终布局)被点击了。然后将我转到另一个由 uniqueViewController.swift 管理的视图控制器。
正是这个视图控制器 (uniqueViewController.swift) 我有一个标签 (uniqueLabel),我希望根据从 ViewController 中单击的布局来更改文本。这是让我难过的整个数据传递部分。任何代码 sn-ps 和指导将不胜感激!谢谢。
ViewController.swift
import UIKit
class CollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
var data = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
data = ["Layout one", "Layout two", "Layout three", "Layout four"]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell = collectionView.dequeueReusableCellWithReuseIdentifier("my cell", forIndexPath: indexPath) as! UICollectionViewCell
var btnLabel = cell.viewWithTag(1) as! UILabel
btnLabel.text = data[indexPath.row]
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//println("Cell \(indexPath.row) tapped")
performSegueWithIdentifier("testSegue", sender: self)
if((indexPath.row) == 0) {
println("Layout 1 clicked")
}
else if((indexPath.row) == 1) {
println("Layout 2 clicked")
}
else if((indexPath.row) == 2) {
println("Layout 3 clicked")
}
else if((indexPath.row) == 3) {
println("Layout 4 clicked")
}
}
}
uniqueViewController.swift
import UIKit
class uniqueViewController: UIViewController {
@IBOutlet weak var uniqueLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
uniqueLabel.text = "I want this labels text unique depending on which cell was tapped from ViewController.swift"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
** 更新**
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
//println("Cell \(indexPath.row) tapped")
performSegueWithIdentifier("testSegue", sender: indexPath.row)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let vc = segue.destinationViewController as? uniqueViewController {
switch(sender as! Int) {
case 0:
vc.uniqueLabel.text = "First"
break
case 1:
vc.uniqueLabel.text = "Second"
break
case 2:
vc.uniqueLabel.text = "Third"
break
case 3:
vc.uniqueLabel.text = "Fourth"
break
default:
println("Index out of range.")
}
}
}
【问题讨论】:
标签: swift uicollectionview cell