以编程方式创建贴纸包,将UICollectionViewCell转换为MSStickerView时出现问题



因此,我选择在消息扩展标签包中不使用故事板。iMessage应用程序附带了一个故事板文件和一个MessagesViewController.swift。我创建了两个名为CollectionViewController和StickerCell的文件。这个想法是将CollectionViewCell子类化,并将其强制转换为MSStickerView,然后将该视图作为"单元格"出列到我的CollectionView中。

以下是将"StickerCell"设置为MSSstickerView:的代码

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let item = data[indexPath.row]
return deQStickerCell(for: item, at: indexPath)
}
private func deQStickerCell(for sticker: MSSticker, at indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView?.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! StickerCell
cell.stickerView.sticker = sticker
return cell
}

以及我的StickerCell类中的代码:

class StickerCell: UICollectionViewCell {
var stickerView: MSStickerView!
}

我猜问题就在这里,因为我已经成功地使用了故事板和StickerClass中的确切代码,除了var是IBOutlet。很明显,有些东西没有连接到CollectionView,或者我错过了一步。在Interface Builder中,我会创建CollectionViewController,给它一个CollectionView,给它个CollectionViewCell,然后在上面加上一个UIView,并将其类更改为MSStickerView。

如何以编程方式重新创建界面生成器工作流!?

很难确切知道你的问题是什么,但据我所知,你不会得到一个具有stickerView子视图的StickerCell。与IB不同的是,您从未初始化过您的stickerView。您需要添加一个init来创建视图并将其添加到您的单元格中。类似(伪代码):

override init(frame: CGRect) {
super.init(frame: frame)
self.stickerView = StickerView()
self.contentView.addSubview(self.stickerView)
// Set up your constraints & layout
}

最新更新