CollectionView 中用于评论和回复的多个单元格

2023-12-02

我有两种不同的单元格类型,一种用于评论,另一种用于回复。我正在尝试以相同的方式呈现它们collectionView然后也许可以像这样对它们进行分组:每个具有特定 id 的评论下面都有其回复。然而,无论什么尝试,我都失败了。

你会怎样做呢?

private var comments = [Comment]()
private var replies = [Reply]()
var items: [Any] = []


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return items.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//        let item = items[indexPath.item]

        var item = items[indexPath.item]

        if item is Comment.Type  {

            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CommentCell.cellId, for: indexPath) as! CommentCell
            cell.comment = items[indexPath.item] as? Comment
            print(item)
            return cell


        } else {
                    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: RepliesCell.cellId, for: indexPath) as! RepliesCell
            cell.reply = items[indexPath.item] as? Reply

                    return cell

        }



    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let item = items[indexPath.item]

        if item is CommentCell.Type {

            let dummyCell = CommentCell(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 50))
            dummyCell.comment = items[indexPath.item] as? Comment
            dummyCell.layoutIfNeeded()

            let targetSize = CGSize(width: view.frame.width, height: 250)
            let estimatedSize = dummyCell.systemLayoutSizeFitting(targetSize)
            let height = max(40 + 8 + 8, estimatedSize.height)

            return CGSize(width: view.frame.width, height: height)
        } else {
            let dummyCell = RepliesCell(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 50))
            dummyCell.reply = items[indexPath.item] as? Reply
            dummyCell.layoutIfNeeded()

            let targetSize = CGSize(width: view.frame.width, height: 250)
            let estimatedSize = dummyCell.systemLayoutSizeFitting(targetSize)
            let height = max(40 + 8 + 8, estimatedSize.height)

            return CGSize(width: view.frame.width, height: height)
        }
     }
}

最佳实践解决方案

创建包含 Replies 对象列表的 Reply 模型和 Comment 模型

class Comment {
    var commentId: Int
    var commentText: String
    var replies: [Reply]

    init(commentId: Int, commentText: String, replies: [Reply]) {
        self.commentId = commentId
        self.commentText = commentText
        self.replies = replies
    }
}

class Reply {
    var replyId: Int
    var replyText: String

    init(replyId: Int, replyText: String) {
        self.replyId = replyId
        self.replyText = replyText
    }
}

为评论标题创建 UICollectionReusableView

class CommentHeader: UICollectionReusableView {

    @IBOutlet weak var commentTextLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    func configure(with comment: Comment) {
        commentTextLabel.text = comment.commentText
    }

}

创建一个 UICollectionViewCell 用于回复

class ReplyCell: UICollectionViewCell {

    @IBOutlet weak var replyTextLabel: UILabel!

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    func configure(with reply: Reply) {
        replyTextLabel.text = reply.replyText
    }

}

创建一个 CommentsViewController 类,其中包含 UICollectionView 和评论数据列表

注意 header 和 cell 是在 viewDidLoad 方法中注册到集合视图中的

class CommentsViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!

    var comments: [Comment] = [Comment]()

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.register(UINib(nibName: "CommentHeader", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "CommentHeaderIdentifier")
        collectionView.register(UINib(nibName: "ReplyCell", bundle: nil), forCellWithReuseIdentifier: "ReplyCellIdentifier")

        comments = getDummyComments(with: 3)
    }

    func getDummyComments(with count: Int) -> [Comment] {

        var comments = [Comment]()
        for i in 1...count {
            comments.append(Comment(commentId: i, commentText: "Comment \(i)", replies: getDummyReplies(with: i)))
        }
        return comments

    }

    func getDummyReplies(with count: Int) -> [Reply] {
        var replies = [Reply]()
        for i in 1...count {
            replies.append(Reply(replyId: i, replyText: "Reply \(i)"))
        }
        return replies
    }
}

最后设置 UICollectionView 数据源和委托方法

extension CommentsViewController: UICollectionViewDataSource {

    // for cell
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return comments.count
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return comments[section].replies.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let replyCell = collectionView.dequeueReusableCell(withReuseIdentifier: "ReplyCellIdentifier", for: indexPath) as! ReplyCell
        replyCell.configure(with: comments[indexPath.section].replies[indexPath.row])
        return replyCell

    }

    // for header
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {

        if kind == UICollectionElementKindSectionHeader {

            let commentHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "CommentHeaderIdentifier", for: indexPath) as! CommentHeader

            commentHeader.configure(with: comments[indexPath.section])
            return commentHeader
        }

        return UICollectionReusableView()
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.frame.width, height: 100) // this height is used for the example, you can use self sizing for height
    }

}

extension CommentsViewController: UICollectionViewDelegateFlowLayout {

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        return CGSize(width: collectionView.frame.width, height: 100) // this height is used for the example, you can use self sizing for height

    }

}

让我们看看评论屏幕:)

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

CollectionView 中用于评论和回复的多个单元格 的相关文章

  • 在 swift 中使用协议作为数组类型和函数参数

    我想创建一个可以存储符合某种协议的对象的类 对象应该存储在类型数组中 根据 Swift 文档 协议可以用作类型 因为它是一种类型 所以您可以在许多允许其他类型的地方使用协议 包括 作为函数 方法或初始值设定项中的参数类型或返回类型 作为常量
  • iOS 15 中表视图标题上方的额外填充

    如何更改上面的额外填充UITableViewiOS 15 中开始出现的节标题 从 iOS 15 开始 UITableView包含一个名为的新属性sectionHeaderTopPadding https developer apple co
  • UICollectionView 上的 UIRefreshControl 仅当集合填充容器的高度时才起作用

    我正在尝试添加一个UIRefreshControl to a UICollectionView 但问题是 除非集合视图填满其父容器的高度 否则刷新控件不会出现 换句话说 除非集合视图足够长需要滚动 否则无法将其下拉以显示刷新控制视图 一旦集
  • 如何在 UIAlertController 中的 UITextField 之后插入 UILabel

    我有一个UIAlertController of alert消息文本的样式 我已经插入了一个UITextFiled在其中与addTextField 现在我想要在它下面有一串文本 我想我需要一个UILabel但我该如何插入它呢 A UIAle
  • 如何使用 Restkit 0.20.0 创建/发布新的托管对象到服务器?

    我很难找到创建新托管对象 设置其值以及使用 Restkit 保存到服务器的文档或示例 我有一篇 NSManagedObject 帖子 interface Post NSManagedObject property nonatomic ret
  • 按钮图像未显示在 UItextfield 的 rightView 中

    我创建了一个按钮图像 并使用 Sa wift 将其放置在 UITextField 密码 的 rightView 上 我想在密码字段中创建切换按钮隐藏 显示安全文本 右视图中显示的图像 Code func passwordToggleButt
  • TabBarController:以不同方向定向视图

    我无法保持当前的观点方向 在下面的设置中 我能够将第一个视图控制器锁定为纵向 将第二个视图控制器锁定为横向或纵向 但是 当我向选项卡控制器添加第二个导航控制器 rootviewcontroller 时 整个项目中的所有视图都将变为横向和纵向
  • 加快 SpriteSheet 的 UIImage 创建速度

    我不确定我的标题是否正确 但我不确定我的问题到底在哪里 我需要从 spritesheet 加载 UIImage 数组 然后将其用作 UIImageView 中的动画 spritesheet是用TexturePacker生成的 它生成巨大的图
  • 使用自定义组件:子类 UIView 或 UIViewController?

    我正在研究 UISegmentedControl 的自定义实现 我想创建一个能够接收配置数据并从中获取类似于 UISegmentedControl 的自定义视图的组件 我开始对 UIView 进行子类化 我可以使用以下代码创建自定义 UIS
  • 在 Interface Builder 中启用/禁用 NSLayoutConstraints

    NSLayoutConstraint in iOS 8 0 has a BOOL属性称为active这使得动态禁用 启用所述布局约束变得容易 要为视图控制器创建第二个布局集 然后我可以以编程方式启用 禁用它 通过IBOutletCollec
  • 将字符串编码为 HTML 字符串 Swift 3

    如何快速编码字符串以删除所有特殊字符并将其替换为其匹配的 html 编号 假设我有以下字符串 var mystring This is my String That s it 然后用它的html编号替换特殊字符 38 39 gt 62 但我
  • 搜索结果中的 Swift 搜索结果控制器连接到另一个视图控制器

    Problem 我有一个表格视图 用户可以滚动查找某些内容或使用搜索栏 搜索栏不是使用 StoryBoard 创建的 我的观点有一个UISearchController处理搜索栏和搜索结果更新 我遇到的问题是 自从我SearchResult
  • 控制 NSLayoutManager 中自定义文本属性周围的间距

    我有一个习惯NSLayoutManager我用来绘制药丸状标记的子类 我使用自定义属性为子字符串绘制这些标记 TokenAttribute 我会画画没有问题 但是 我需要在范围周围添加一些 填充 TokenAttribute 这样标记的圆角
  • UIButton 图像调整大小/缩放以适合

    我有一个非常严重的问题 我不知道如何解决 我正在对 UIButtons 框架进行动画处理 当我对其进行动画处理时 我希望按钮中的图像缩放到与按钮相同的大小 它无需在我的 iPhone 模拟器上执行任何操作即可运行 但是当我在 iPad 模拟
  • 如何模拟应用程序在后台被杀死?

    我试图验证我的应用程序 App1 在启动另一个应用程序 App2 后被系统关闭时行为是否正确 有什么方法可以模拟或强制这种行为吗 在 App2 运行时告诉模拟器模拟内存警告不会执行任何操作 直到 App1 返回前台为止 从调试器中杀死 Ap
  • 关于 Swift 中重写类属性的困惑

    我已阅读 Swift 文档并在这里搜索 但我仍然不确定如何实现类层次结构 其中每个子类为继承的静态属性设置自定义值 那是 基类定义了一个静态属性 所有实例共享相同的值 子类覆盖静态属性 所有实例共享相同的值 这与基类不同 财产可以储存吗 另
  • 使用 CommonCrypto 的 Swift AES 加密

    我正在开发一个 iOS 应用程序代码7 1 with 斯威夫特2 1我正在尝试进行简单的加密AES 128 位 and PKCS7填充使用通用加密库 该代码有效 但每次我尝试投射NSData反对NSString然后对于 String 我得到
  • NSPredicate predicateWithFormat 传入属性名称

    关于 NSPredicate 的简单问题 我正在尝试使用 传入 值构建我的谓词 如下所示 NSPredicate currentPredicate NSPredicate predicateWithFormat key changesDic
  • Swift 中的 id 相当于什么?

    我有两个这样的代表 protocol MyFirstDelegate func change value int protocol MySecondDelegate weak var delegate MyFirstDelegate 这些协
  • 在 HStack 中以正确的方式对齐两个 SwiftUI 文本视图

    我有一个包含两行的简单列表视图 每行包含两个文本视图 查看一和查看二 我想对齐每行中的最后一个标签 查看两个 以便名称标签领先对齐并保持对齐 无论字体大小如何 第一个标签 查看一个 也需要前导对齐 我尝试在第一个标签 查看一个 上设置最小框

随机推荐