如何从不同的方法访问 UICollectionViewCell 中标签的文本?
Posted
技术标签:
【中文标题】如何从不同的方法访问 UICollectionViewCell 中标签的文本?【英文标题】:How to access text of a label in a UICollectionViewCell from a different method? 【发布时间】: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 语句列表。
【参考方案1】:
cellForItemAtIndexPath 在要显示时为每个项目调用。您正在对字符串数组应用某种“洗牌”?因此,并非所有字符串都必须使用,并且一些字符串将具有相同的文本。 您可以简单地全局初始化变量“定义”和“船”,然后像这样访问值:
if indexPath.item < 7
selectedText = definitions[indexPath.item]
else
selectedText = boatTypes[indexPath.item]
【讨论】:
谢谢!这解决了我的问题!编码也少得多:)以上是关于如何从不同的方法访问 UICollectionViewCell 中标签的文本?的主要内容,如果未能解决你的问题,请参考以下文章
UICollectionView - 如何在同一部分显示不同高度的项目?
如何从不同的 button_click 访问一个 button_click 内的数组?