ios - Swift 中如何处理 UITableViewCell 中可能存在也可能不存在的元素?

标签 ios swift uitableview

假设我正在编写一个 Twitter 克隆,用户可以在其中发布消息和照片。我在 UITableView 中呈现推文。对于有照片的推文,我会将这些照片放在 UICollectionView 中,将其称为 photoCollectionView 并且此 UICollectionView 是单元格的 subview 。问题是,如果一条推文没有任何照片怎么办?如何隐藏 photoCollectionView 并动态设置单元格高度?到目前为止,我可以想到 2 个选项:

选项 1:使用 Storyboard和自动布局。在我的 Storyboard中,无论如何添加 photoCollectionView,但使其 height = 0。但是,我必须设置约束,因为这是我能够使用 tweetTableView.rowHeight = UITableViewAutomaticDimension 的方式。因此,我为 photoCollectionView 设置了顶部、左侧、右侧、高度限制。然后在 TweetCell 类中我有:

class TweetCell: UITableViewCell {
    @IBOutlet weak var photoCollectionView: UICollectionView!

    var photos: [UIImage]? {
        didSet {
            if let assets = photos {
                photoCollectionView.delegate = self
                photoCollectionView.frame.size.height = <Some number>
            } else {
                photoCollectionView.frame.size.height = 0
            }
        }
    }

    override func prepareForReuse() {
        photoCollectionView.delegate = nil
        photoCollectionView.frame.size.height = 0
    }
}

extension TweetCell: UICollectionViewDelegate, UICollectionViewDataSource {
    ...
}

选项 2:不要将其添加到 Storyboard中:

class TweetCell: UICollectionViewCell {
    private var photoCollectionView: UICollectionView?
    var photos: [UIImage]? {
        didSet {
            if let assets = photos {
                photoCollectionView = UICollectionView.init(...)
                photoCollectionView.delegate = self
            }
        }
    }

    // Then pretty much the same as above
}

然后,在我呈现所有推文的 TweetTableViewController 中,我需要手动设置行高:

override func cellHeightForRowAt (indexPath: IndexPath) -> CGFloat {
    let cell = tweetTableView.cellForRow(at: indexPath) as? TweetCell
    if let photos = cell?.photos {
        return <Some number>
    }

    return 20    // Suppose default height is 20, to display other info
}

这两种选择都能满足我的需求,但是有更好的方法吗?这种方式似乎不是很有效:

  1. 选项 1 使用 prepareForReuse,根据 Developer Guide , 我应该只重置与内容无关的属性。

  2. 选项 2 动态添加 UICollectionView,如果用户快速滚动怎么办?

最佳答案

选项 3:有两个原型(prototype)单元格。一种用于带照片的推文,一种用于不带照片的推文。根据您在 cellForRowAt 中的数据将适当的单元格出队。

只要给他们不同的标识符,然后你就可以根据标识符出列你想要的那个。

关于ios - Swift 中如何处理 UITableViewCell 中可能存在也可能不存在的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50421002/

相关文章:

android - react-native handle device "share to"特性 iOS/android

ios - 在 Swift 中单击添加和删除按钮时如何在 View 上添加和删除文本字段?

ios - 在 TextField iOS 中按退格键/删除键

swift - 如何在 Xcode 12 beta 3 中使用 Swift 成功导入 AVFoundation?

ios - uitableviewcells 中的重复内容

ios - MKMapView 改变当前位置飞艇颜色

ios - 使用 Restkit 通过外键连接一对多

swift - Promise.onSuccess 立即调用

iphone - 在 cellForRowInIndexPath 中创建数组

ios - 如何在滚动TableView中加载单元格?