Swift - пользовательский UILabel в UICollectionViewCell - PullRequest
1 голос
/ 04 ноября 2019

У меня есть UICollectionView, где я могу добавить cell, нажав. Моя цель состоит в том, чтобы пользователь мог выбрать имя ячейки, но я изо всех сил пытаюсь это сделать.

Это моя главная страница:

enter image description here

Я реализовал всплывающее окно, которое появляется, если пользователь нажимает addCell, который выглядиткак это:

enter image description here

Нажав на addCell, создается другая ячейка, которая выглядит без всплывающего окна:

enter image description here

Вопрос:

Как мне связать всплывающее текстовое поле с UILabel в моем cell? («Метка теста» на 3-м рисунке)

Ячейка должна быть создана только после нажатия «Liste erstellen» - Button (2-е изображение)

Вот мой код для добавленияячейка и всплывающее окно (всплывающее окно с раскадровкой):

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    // if item is less that data count, return a "Content" cell
   // data count checking, so "Wish List" cell will always
   // be displayed first, "Add Item" cell displayed last

   // if item is Zero (the first cell to be displayed), show the "Wish List" cell
   if indexPath.item == 0 {
       let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MainWishlistCell", for: indexPath) as! MainWishlistCell
       return cell
   }

   // if item is less than or equal to data count, return a "Content" cell
   // arrays are zero-based, so get the data element from item -1
   else if indexPath.item <= theData.count {
       let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ContentCell", for: indexPath) as! ContentCell
       cell.theLabel.text = theData[indexPath.item - 1]
       return cell
   }

   // past the end of the data count, so return an "Add Item" cell
   let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "AddItemCell", for: indexPath) as! AddItemCell

   // set the closure
   cell.tapCallback = {
       print("tapped addButton")

    UIView.animate(withDuration: 0.25) {
        self.blurrImage.alpha = 0.96
        self.newListView.alpha = 1
        self.newListTextfield.alpha = 1
        self.view.layoutIfNeeded()
    }
        // add item button was tapped, so append an item to the data array
        self.theData.append("\(self.theData.count + 1)")
        // reload the collection view
        collectionView.reloadData()
        collectionView.performBatchUpdates(nil, completion: {
            (result) in
            // scroll to make newly added row visible (if needed)
            let i = collectionView.numberOfItems(inSection: 0) - 1
            let idx = IndexPath(item: i, section: 0)
            collectionView.scrollToItem(at: idx, at: .bottom, animated: true)
        })

   }

   return cell

}

И это мой код для cell:

class ContentCell: UICollectionViewCell {
let testImage: UIImageView = {
    let v = UIImageView()
    v.translatesAutoresizingMaskIntoConstraints = false
    v.backgroundColor = .cyan
    return v
}()

let theLabel: UILabel = {
    let v = UILabel()
    v.translatesAutoresizingMaskIntoConstraints = false
    v.textAlignment = .center
    return v
}()

let testLabel: UILabel = {
    let v = UILabel()
    v.translatesAutoresizingMaskIntoConstraints = false
    v.text = "Test Label"
    v.font = UIFont(name: "AvenirNext-Medium", size: 18)
    v.textColor = .darkGray
    v.textAlignment = .center
    return v
}()

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

required init?(coder: NSCoder) {
    super.init(coder: coder)
    commonInit()
}


func commonInit() -> Void {
    contentView.layer.cornerRadius = 3.0;
    contentView.addSubview(testLabel)
    contentView.addSubview(testImage)
    // constrain label to all 4 sides
    NSLayoutConstraint.activate([

        testImage.topAnchor.constraint(equalTo: contentView.topAnchor),
        testImage.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
        testImage.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
        testImage.heightAnchor.constraint(equalToConstant:150),

        testLabel.topAnchor.constraint(equalTo: testImage.bottomAnchor,constant: 1),
        testLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
        testLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
        testLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
    ])
    }
}
...