ios - 在以编程方式添加的 UICollectionViewCell 中看不到 UILabel

标签 ios swift uicollectionview uicollectionviewcell

当用户在我的 CollectionView 上启动 PanGesture 以重新排序单元格时,我以编程方式创建了一个 UICollectionViewCell(我不使用 Apple API,因为我必须个性化行为)。

我从具有 IBOutlet 的自定义类 WordCollectionViewCell 创建一个 Cell。这是类的代码:

class WordCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var wordLabel: UILabel!
}

要创建单元格并将其添加到 CollectionView,我使用以下代码:

    self.movingCell = {
        let mC = WordCollectionViewCell(frame: selectedCell.frame)

        // I HAVE TO DO THIS WITH A VARIABLE BECAUSE IF I ASSIGN UILabel() DIRECTLY TO mC.wordlabel, THE APP CRASH BECAUSE wordLabel IS NIL
        let label = UILabel()
        mC.wordLabel = label


        mC.wordLabel.text = selectedCell.wordLabel.text
        mC.addSubview(mC.wordLabel)

        mC.backgroundColor = selectedCell.backgroundColor
        mC.layer.cornerRadius = selectedCell.layer.cornerRadius
        mC.tag = selectedIndexPath.row
        return mC
    }()

    self.collectionView.addSubview(self.movingCell)

    self.collectionView.addConstraint(NSLayoutConstraint(item: movingCell.wordLabel, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: movingCell, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0))
    self.collectionView.addConstraint(NSLayoutConstraint(item: movingCell.wordLabel, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: movingCell, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0))
    self.collectionView.addConstraint(NSLayoutConstraint(item: movingCell.wordLabel, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: movingCell, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 0))
    self.collectionView.addConstraint(NSLayoutConstraint(item: movingCell.wordLabel, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: movingCell, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: 0))

Cell 将跟随 PanGesture 的位置。

这段代码有两个问题:

  1. 我在设备上的 movingCell 测试中看不到任何东西;
  2. 为什么我不能将 UILabel() 直接设置为 wordLabel

最佳答案

尝试添加 label.translatesAutoresizingMaskIntoConstraints = false

关于ios - 在以编程方式添加的 UICollectionViewCell 中看不到 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40048327/

相关文章:

SwiftUI 以编程方式从可表示返回到 View

ios - UICollectionViewCompositionalLayout 不能使用与 UICollectionViewDiffableDataSource 相同的部分吗?

ios - 异步加载uitableview中的照片

ios - 将 UIButton 添加到 UITableViewCell 以防搜索无结果,空数组

swift - 在 Swift 中添加后接收 UILocalNotification

ios - UITableView 可见单元自动布局后计算 View 位置

ios - 为什么约束不起作用?

ios - UICollectionView:滚动到顶部并在滚动完成时执行操作

ios - 投票:投票登记两次

ios - 我想将 Table View 精确放置到导航栏