当用户在我的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位置。
使用此代码有两个问题:
movingCell
测试中看不到任何内容; UILabel()
直接设置为wordLabel
? 答案 0 :(得分:1)
尝试添加label.translatesAutoresizingMaskIntoConstraints = false