首页 > 解决方案 > 如何自定义collectionView单元格?

问题描述

我是 Swift 的新手。我想使用 UICollectionView 创建一个简单的填充词应用程序。当答案有 2 个单词(如“Hello World”)时,我如何自定义 UICollectionViewCell。我希望“世界”将进入下一行。请告诉我如何将表示“Hello”和“World”的单元格居中?感谢您的帮助。这是我的代码:

    var arrayCharacter = ["H","E","L","L","O","W","O","R","L","D"]
    extension QuestionVC: UICollectionViewDelegate, UICollectionViewDataSource {
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return arrayCharacter.count
        }

        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "quizColCell", for: indexPath) as! QuizCollectionCell
            cell.lblCharacter.text = arrayCharacter[indexPath.row]
            return cell
        }
    }

在此处输入图像描述

标签: iosswiftuicollectionview

解决方案


我能想到的 2 种方法:
第一种方法- 考虑重新设计 DATA 来自:
var arrayCharacter = ["H","E","L","L","O","W","O"," R","L","D"]。

var arrayWords = [ "HELLO", "WORLD"]

每个 collectionViewCell 将代表一个 WORD。
每个单元格将是 1 行(全宽) 在该单元格中,您将为每个字母创建标签(并隐藏您不用于单词的标签)

第二种方式,通过使用 SECTIONS(谷歌 collectionView 部分)。
数据需要是:
数组数组:
sections[0] = ["h","e", "l","l","o"]。
部分[1] = ["w","o","r","l","d"]


推荐阅读