繁体   English   中英

如何在collectionView单元格中初始化结构?

[英]How to initialize a struct in a collectionView cell?

我有一个collectionView在所有单元格中设置cellForItemAt的地方:

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 IBAction方法的注释中查看错误消息:实例成员'ID'不能用于类型'SNPostViewCell.cellPost'

如何正确初始化此结构?

当需要SNPostViewCell.cellPost对象(该类型的实例)时, thisPost类型为SNPostViewCell.cellPost.Type ,它是实际的类类型。 这是因为您要使用.self进行分配。

要解决此问题,变量声明应更改为:

var thisPost: cellPost?

然后在您的cellForItemAt方法中,您将设置cellPost对象,如下所示:

cell.thisPost = cellPost(ID: post.id, notes: post.notes, tags: Array(post.tags.keys))

您还需要在editButtonPressed方法中处理可选类型。 另外,您可以为单元格提供thisPost的默认值,并删除?。 从变量类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM