简体   繁体   中英

How to initialize a struct in a collectionView cell?

I have a collectionView where I set cellForItemAt in all the cells:

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

Then in my cell I have:

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

As you can see I am trying to set a struct so that I can use it in delegate methods for instance that I create and use in the view controller. However my instantiation doesn't work. Look at the error message in the comment in the editPost IBAction method: Instance member 'ID' cannot be used on type 'SNPostViewCell.cellPost'

How do I initialize this struct properly?

thisPost is type SNPostViewCell.cellPost.Type , the actual class type, when you are wanting a SNPostViewCell.cellPost object, an instance of the type. This is because you are assigning it with the .self .

To fix this, the variable declaration should be changed to:

var thisPost: cellPost?

Then in your cellForItemAt method, you'll set the cellPost object like this:

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

You'll need to handle the optional type in the editButtonPressed method as well. Alternatively, you could give the cell a default value for thisPost and remove the ? from the variable type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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