2016-05-29 95 views
0

当用户选择一个单元格时,我想获得其特定的UIViews之一并更改其颜色。无法获取单元格子视图?

所以,

 func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { 

       for cell in collectionView.visibleCells() as [UICollectionViewCell] 
      { 


        if(cell.tag==indexPath.row) 
        { 
         for view in [cell.contentView.subviews] { 

         view.backgroundColor=UIColor.redColor() 

     //here what ever I try I can't get it to see view as a UIView and change its properties, instead I get error that [UIView] has no member.. 

回答

0

这为我工作:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 
{ 
    var selectedCell:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)! 
    selectedCell.contentView.backgroundColor = UIColor.redColor() 
} 

如果tableView在属性检查器中设置与选择,以多种选择它应该工作。只需将其取消选择:

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) 
{ 
    var cellToDeSelect:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)! 
    cellToDeSelect.contentView.backgroundColor = colorForCellUnselected 
} 
0

有一个更简单的方法来做到这一点。简单地获取您感兴趣的单元格,然后直接操作它。使用标签是一种脆弱的方法。此外,当您通过另一个视图的子视图迭代,你已经处理一个数组,就没有必要把它包起来的[]中

if let cell = tableView.cellForRowAtIndexPath(indexPath) { 
    for view in cell.contentView.subviews { 
     view.backgroundColor = UIColor.redColor() 
    } 
    } 
+0

这不是工作,这是我已经开始具有明显的方式。在最新的Swift上,你会看到一个错误,因为视图不被识别为UIView。 – Curnelious

-1

cell.contentView.subViews是一个数组中这样view会变成是一个数组。

宽松周边[]这样的:

for view in cell.contentView.subviews { 
     view.backgroundColor=UIColor.redColor() 
} 
+0

最初的答案对不起,读错了 – Cjay

相关问题