【发布时间】:2014-12-17 21:48:17
【问题描述】:
我有一个UICollectionViewController 类型的类。在这个类中,我有一个UICollectionViewCell 标签的变量:
var cellTitle = UILabel()
我也有collectionView方法cellForItemAtIndexPath:
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as UICollectionViewCell
var definitions = shuffle(["Used to carry the pharoah","Used to carry bodies as a ceremony","Had a flat deck to carry a farmer's treasure","Daily, it made a trip around the world to carry Ra","Towed by smaller boats, carrying heavy objects","Used for business and pleasure by officials/nobles","Carried most Egyptians and some goods"])
var boatTypes = shuffle(["Ferry","Funeral Barge","Cargo Boat","Cattle Boat","Royal Boat","The Sun Boat","Grand Boat"])
// Configure the cell
cellTitle = UILabel(frame: CGRectMake(0, 0, cell.bounds.size.width, 160))
cell.contentView.addSubview(cellTitle)
switch indexPath.item {
case 0:
cellTitle.text = definitions[0]
case 1:
cellTitle.text = definitions[1]
case 2:
cellTitle.text = definitions[2]
case 3:
cellTitle.text = definitions[3]
case 4:
cellTitle.text = definitions[4]
case 5:
cellTitle.text = definitions[5]
case 6:
cellTitle.text = definitions[6]
case 7:
cellTitle.text = boatTypes[0]
case 8:
cellTitle.text = boatTypes[1]
case 9:
cellTitle.text = boatTypes[2]
case 10:
cellTitle.text = boatTypes[3]
case 11:
cellTitle.text = boatTypes[4]
case 12:
cellTitle.text = boatTypes[5]
case 13:
cellTitle.text = boatTypes[6]
default:
break
我还有一个didSelectItemAtIndexPath 方法:
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
var selectedText = cellTitle.text
switch indexPath.item {
case 0:
if selectedText == "Used to carry the pharoah" {
println("Used to carry the pharoah")
} else {
println("Not Working")
}
问题是,当我按下标签上确实有“用于携带法老”文本的单元格时,会触发println("Not Working")。如何将cellForItemAtIndexPath 方法中的值传递给didSelectItemAtIndexPath 方法,使cellTitle 的值保持不变?谢谢。
【问题讨论】:
-
您可以使用传递给函数的
indexPath来检索单元格,但不要这样做。相反,使用 indexPath 直接转到您的数据模型(在本例中为数组) - 但您应该将数组移出cellForItemAtIndexPath函数 - 继续重新定义数组非常低效。你也可以用一个 if 替换那个 case 语句列表。
标签: ios swift uicollectionviewcell nsindexpath textlabel