使用guard / if语句来设置多个CollectionvViewCells样式的好习惯吗?

时间:2017-01-14 19:17:51

标签: swift xcode uiscrollview uicollectionview

我有一个困境,我在CollectionView每个collectionviewcell显示不同的数据并且具有不同的边框/背景样式。例如,代码段

let monsters: Monsters!


    cell.graphViewIBO.isHidden = true
    cell.monsblIBO.isHidden = true
    cell.powersBgIBO.isHidden = true


    guard indexPath.row != 0 else {

        cell.indexOne(monsters)
        return cell
    }
    guard indexPath.row != 1 else {

        cell.indexTwo(monsters)
        return cell
    }
    guard indexPath.row != 2 else {

        cell.indexThree(monsters)
        return cell
    }

我觉得这可能是不好的做法,我不确定是否应该继续这样做,或者只是使用scrollview并在其中单独设置uiview个样式。 因为从右到底,我的故事板包含一个collectionviewcell中的几个对象,我需要隐藏/显示这些对象,具体取决于呈现的索引。我可以继续使用CollectionView吗?这种方法的正确方法是什么方法?

1 个答案:

答案 0 :(得分:0)

我认为你想要使用的是switch语句。您的代码如下所示:

let monsters: Monsters!

cell.graphViewIBO.isHidden = true
cell.monsblIBO.isHidden = true
cell.powersBgIBO.isHidden = true

switch indexPath.row {
case 0:
    cell.indexOne(monsters)
case 1:
    cell.indexTwo(monsters)
case 2:
    cell.indexThree(monsters)
default: break
}

return cell

如果要更改单元格,可以创建UICollectionViewCell的不同子类,您可以根据索引创建这些子类。如果您只使用每种类型的单元格一次,那么UIScrollView会更好。但是,如果您多次使用相同类型的单元格(例如只更改一些文本),则应使用UICollectionView。