как положить символ в отдельной коллекции ViewCell в Swift - PullRequest
1 голос
/ 15 апреля 2020

введите описание изображения здесь Я делаю игру в слова, у меня есть слово, это слово нужно разделить на символы, и каждый персонаж должен быть добавлен в отдельную ячейку, и между ними должен быть пробел. слова, при использовании пользовательского класса для метки. Для этого я использую коллекцию ячеек, я не мог добавить символ в каждую ячейку, я мог только передать целое слово в каждую ячейку. Пожалуйста, помогите решить эту проблему.

PS Я добавил скриншоты в порядке и как он есть введите описание изображения здесь

Мой код

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")
    }
}

1 Ответ

1 голос
/ 17 апреля 2020

Проблема в том, что вы устанавливаете cell.label.text на word в каждой ячейке. Просто разбейте фразу на компоненты и добавьте их в массив. В моем примере я упростил его.

Вероятно, вам потребуется адаптировать его к вашему приложению, но вот быстрая реализация, чтобы вы только начали.

import UIKit

class ViewController: UIViewController {

    let cellID = "Cell"
    let word = "Hello My People"
    var arr = [String]()

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

    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.backgroundColor = .brown
        view.addSubview(collectionView)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(UICollectionViewCell.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

        for char in word {
            arr.append(String(char))
        }

    }


}

extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return arr.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath)
        cell.backgroundColor = .red
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        let cellText = arr[indexPath.item]
        lbl.text = cellText
        if cellText == " " {
            cell.backgroundColor = .clear
        }
        cell.addSubview(lbl)

        lbl.centerXAnchor.constraint(equalTo: cell.centerXAnchor).isActive = true
        lbl.centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = true

        return cell
    }

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

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

Результат:

Final Output

...