无法以编程方式添加UICollectionViewCell中的UILabel

时间:2016-10-14 16:53:34

标签: 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

1 个答案:

答案 0 :(得分:1)

尝试添加label.translatesAutoresizingMaskIntoConstraints = false