问题描述
我正在开发一个"交易"应用程序,我希望在其中拥有静态数量的单元格.
加载时,用户会看到 5 个单元格,每个单元格都显示一个标有"添加"的标签.
添加"玩家"后,该单元格显示玩家信息,其他 4 个单元格仍显示"添加"标签.另一个是添加的,2个单元格有玩家信息,3个有"添加"
我玩得很开心.谁能指出我正确的方向?我有自定义标签设置,我认为我的逻辑可能只是关于如何正确执行此操作.
推荐答案
你需要在你的viewController中继承UICollectionViewDelegate和UICollectionViewDataSource协议,然后你需要实现numberOfItemsInSection 和 cellForItemAtIndexPath 函数.除此之外,您需要在情节提要中创建两种类型的单元格并将它们子类化,在下面的代码中,我将假设您调用 AddedPlayerCell 和 DefaultCell 您的单元格,我会假设每个单元格也有一个名为 labelText 的标签.
let players = ["Player1","Player2"] //players added till now let numberOfCells = 5 //Here you set the number of cell in your collectionView func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return max(players.count,numberOfCells); } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if((indexPath.row + 1) < self.players.count){ //If index of cell is less than the number of players then display the player let cell = collectionView.dequeueReusableCellWithReuseIdentifier("yourIdentifierForAddedPlayerCell", forIndexPath: indexPath) as! AddedPlayerCell cell.labelText.text = self.players[indexPath.row] //Display player return cell; }else{//Else display DefaultCell let cell = collectionView.dequeueReusableCellWithReuseIdentifier("yourIdentifierForDefaultCell", forIndexPath: indexPath) as! DefaultCell cell.labelText.text = "Add" return cell; } }
相关问答
相关标签/搜索