Ios 如何在collectionView单元格中初始化结构?
我有一个collectionView,其中我在所有单元格中设置了cellForItemAt:Ios 如何在collectionView单元格中初始化结构?,ios,swift,uicollectionview,Ios,Swift,Uicollectionview,我有一个collectionView,其中我在所有单元格中设置了cellForItemAt: func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if collectionView == self.collectionView { let post = posts[in
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.collectionView {
let post = posts[indexPath.row]
print(post,"mypost")
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! SNPostViewCell
cell.isVideo = post.isVideo
cell.postId = post.id
//let tokens = self.tags.map(
let tokensArr = post.tags.keys.map({
(key: String) -> KSToken in
return KSToken.init(title: key)
})
cell.thisPost.init(ID: post.id, notes: post.notes, tags: Array(post.tags.keys))
cell.delegate = self
在我的牢房里我有:
class SNPostViewCell: UICollectionViewCell, UITextViewDelegate {
var thisPost = cellPost.self
struct cellPost {
let ID: String?
let notes: String?
let tags: [String]?
}
@IBAction func editButtonPressed(_ sender: Any) {
self.delegate?.editButtonPressed(postID: thisPost.ID, notes: thisPost.notes, tokens: thisPost.tags) //Instance member 'ID' cannot be used on type 'SNPostViewCell.cellPost'
}
...
protocol SNPostViewCellDelegate {
func editButtonPressed(postID: String, notes: String, tokens: [KSToken])
}
如您所见,我正在尝试设置一个结构,以便可以在委托方法中使用它,例如,我在视图控制器中创建和使用的委托方法。但是,我的实例化不起作用。查看editPost iAction方法中注释中的错误消息:实例成员“ID”不能用于类型“SNPostViewCell.cellPost”
如何正确初始化此结构
thisPost
是类型SNPostViewCell.cellPost.type
,当您需要一个SNPostViewCell.cellPost
对象时,它是实际的类类型,是该类型的一个实例。这是因为您正在使用.self
分配它
要解决此问题,应将变量声明更改为:
var thisPost: cellPost?
然后在cellForItemAt
方法中,将cellPost对象设置如下:
cell.thisPost = cellPost(ID: post.id, notes: post.notes, tags: Array(post.tags.keys))
您还需要在editbutonpressed
方法中处理可选类型。或者,您可以为该单元格指定thisPost的默认值,并删除?从变量类型