当用户在我的 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
?
最佳答案
尝试添加 label.translatesAutoresizingMaskIntoConstraints = false
关于ios - 在以编程方式添加的 UICollectionViewCell 中看不到 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40048327/