代码之家  ›  专栏  ›  技术社区  ›  BigBoy1337

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

  •  0
  • BigBoy1337  · 技术社区  · 7 年前

    我有一个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”

    如何正确初始化此结构?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Sean Kladek    7 年前

    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))
    

    您需要在 editButtonPressed 方法也是。或者,您可以为该单元格指定thispost的默认值并删除?从变量类型。