如何快速将字符放入单独的collectionViewCell中

问题描述 投票:1回答:1

enter image description here我做单词游戏,我有一个单词,这个单词需要分成多个字符,每个字符都应添加到一个单独的单元格中,并且单词之间要留有空格,同时使用自定义类标签。为此,我使用了集合视单元,我无法向每个单元中添加字符,只能将整个单词传输到每个单元中。请帮助解决此问题。

P.S,我按原样添加了屏幕截图enter image description here

我的代码

ViewController.swift

import UIKit

class ViewController: UIViewController {

    let cellID = "Cell"
    let word = "Hello My People"
    var index = 0
    var targets = [TargetView]()

    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 12
        layout.minimumInteritemSpacing = 3
        let collectionView1 = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView1.backgroundColor = .red
        collectionView1.translatesAutoresizingMaskIntoConstraints = false
        return collectionView1

    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .brown
        view.addSubview(collectionView)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(CharCell.self, forCellWithReuseIdentifier: cellID)

        collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16).isActive = true
        collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16).isActive = true
        collectionView.topAnchor.constraint(equalTo: view.topAnchor, constant: 400).isActive = true
        collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -70).isActive = true

        //var anagram1 = word.count



    }


}

extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//
//        var anagram1 = word
//        //var leg = anagram1.count
////
////         //targets = []
//        for (index,letter) in anagram1.enumerated() {
//                      let target = TargetView(letter: letter, sideLength: 15)
//                      if letter != " " {
//                         // let target = TargetView(letter: letter, sideLength: 15)
////                          target.center = CGPoint(x: xOffset + CGFloat(index) /* * 20 */ * (15 + tileMargin) - view.frame.minX, y: UIScreen.main.bounds.size.height - 100) //100 //UIScreen.main.bounds.size.height - CGFloat(index) * 50
////
////                         view.addSubview(target)
////
//                        //targets.append(target)
//                          //stackView.addArrangedSubview(target)
//                          targets.append(target)
//                       return 15
//                     }
//                  }


                  if index < word.count {
                      return word.count
                    } else {
                       return 0
                  }
                   //return 10


        }



    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! CharCell
           for (index,letter) in word.enumerated() {
               let target = TargetView(letter: letter, sideLength: 15)
                   if letter != " " {
                    // let target = TargetView(letter: letter, sideLength: 15)


                    targets.append(target)
                    cell.label.text = String(letter)

            }
    }

        cell.label.text = word

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 30, height: 30)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
           return UIEdgeInsets(top: 15, left: 0, bottom: 0, right: 0)
       }


  }

CharCell.swift

import UIKit

class CharCell: UICollectionViewCell {

    var label1 = [TargetView]()

    lazy var label: UILabel = {
        let label = UILabel()
        label.backgroundColor = .cyan
        label.textAlignment = .left
        label.font = .boldSystemFont(ofSize: 10)
        label.text = "_"//String(letter).uppercased()
        label.textColor = .black
        label.numberOfLines = 3
        return label
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupCell()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setupCell() {
        backgroundColor = .white
        label.frame = CGRect(x: 0, y: 1, width: frame.width , height: frame.height )
        self.addSubview(label)


    }
}

TargetView.swift

import UIKit

class TargetView: UILabel {

    var letter: Character!
    var isMatch = false


    init(letter: Character, sideLength: CGFloat) {
        self.letter = letter

        //let image = UIImage(named: "slot")
        //super.init(image: image)
        //let scale = CGRect(x: 0, y: 0, width: (image?.size.width)! * scale, height: (image?.size.height)! * scale)
        super.init(frame: CGRect(x: 0, y: 0, width: 15, height: 30))
        self.backgroundColor = .red
        self.textAlignment = .center
        self.font = .boldSystemFont(ofSize: 60.0 / 3)
        self.text = "_"//String(letter).uppercased()
        self.textColor = .white
        self.lineBreakMode = .byWordWrapping
        self.adjustsFontSizeToFitWidth = true
        self.translatesAutoresizingMaskIntoConstraints = false

    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
swift string char uikit uicollectionviewcell
1个回答
0
投票

问题是您在每个单元格中都将cell.label.text设置为word。只需将短语拆分为组件并将其添加到数组即可。在我的示例中,我对其进行了简化。

© www.soinside.com 2019 - 2024. All rights reserved.