如何使用 switch 语句在 Swift 中实现 collectionView 功能?

2023-12-22

我是 swift 新手,试图在 ViewController 中实现 collectionView 函数。现在我有三种类型的 UICollectionViewCell,这是我的代码:

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

    if collectionView == self.collectionViewCategory {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: categoryIdentifier, for: indexPath as IndexPath) as! CategoryCell

        cell.CategoryIcon.image = self.categoryItems[indexPath.item]
        cell.layer.borderColor = UIColor.lightGray.cgColor
        cell.layer.borderWidth = 1
        cell.layer.cornerRadius = 5

        return cell
    }
    else if collectionView == self.collectionViewHour {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: hourIdentifier, for: indexPath as IndexPath) as! HourCell

        cell.hourItem.text = self.hourItems[indexPath.item]
        cell.layer.borderColor = UIColor.lightGray.cgColor
        cell.layer.borderWidth = 1
        cell.layer.cornerRadius = 5

        return cell
    }
    else {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: minuteIdentifier, for: indexPath as IndexPath) as! MinuteCell

        cell.minuteItem.text = self.minuteItems[indexPath.item]
        cell.layer.borderColor = UIColor.lightGray.cgColor
        cell.layer.borderWidth = 1
        cell.layer.cornerRadius = 5

        return cell
    }
}

我可以使用switch语句来达到同样的效果吗?让代码看起来更优雅一点?

我希望我的代码看起来像这样:

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

    let cell:UICollectionViewCell

    switch collectionView {
        case self.collectionViewCategory:
            cell = collectionView.dequeueReusableCell(withReuseIdentifier: categoryIdentifier, for: indexPath as IndexPath) as! CategoryCell
            cell.CategoryIcon.image = self.categoryItems[indexPath.item]
        case self.collectionViewHour:
            cell = collectionView.dequeueReusableCell(withReuseIdentifier: hourIdentifier, for: indexPath as IndexPath) as! HourCell
            cell.hourItem.text = self.hourItems[indexPath.item]
        default:
            //do nothing.
    }
    cell.layer.borderColor = UIColor.lightGray.cgColor
    cell.layer.borderWidth = 1
    cell.layer.cornerRadius = 5
    return cell
}

但我犯了很多错误,我不知道如何纠正。


您可以尝试为每个 collectionView 分配一个唯一的标签,如下所示

collectionView.tag = 1

然后使用标签作为标识符:

switch collectionView.tag {
    case 0:
        // some code
    case 1:
        // some code
    default:
        // some code
}

如果你在里面使用你的collectionViewsUITableViewCell您可以设置每个collectionView.tag to be indexPath.section or indexPath.row within tableView(_ tableView: willDisplay cell: forRowAt indexPath:).

这是您可以使用的一个很好的子类:

class CollectionViewTableViewCell: UITableViewCell {
    @IBOutlet weak var collectionView: UICollectionView!

    func setCollectionViewDataSourceDelegate(dataSource: UICollectionViewDataSource?, dataDelegate: UICollectionViewDelegate?, forSection section: Int) {

        collectionView.delegate = dataSource as! UICollectionViewDelegate?
        collectionView.dataSource = dataDelegate as! UICollectionViewDataSource?
        collectionView.tag = section
        collectionView.reloadData()
    }
}

然后在你的视图控制器中实现

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    guard let tableViewCell = cell as? CollectionViewTableViewCell else { return }
    tableViewCell.setCollectionViewDataSourceDelegate(dataSource: self, dataDelegate: self, forSection: indexPath.section)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 switch 语句在 Swift 中实现 collectionView 功能? 的相关文章

  • 当现有的转换或演示正在进行时;导航堆栈不会更新

    我遇到过这个警告 PushViewController animated 在现有转换或演示文稿运行时调用 发生 导航堆栈不会更新 当试图打电话时navigationController popViewControllerAnimated f
  • 如何使用 Swift 将高分游戏保存在排行榜上?

    我使用 SpriteKit 和 Xcode 7 beta 制作了一个游戏 我尝试放置 GameCenter 和 Leaderboard 但问题是排行榜中的分数不会改变 它始终保持 0 游戏的高分不会保存在 Leaderboard 中 我不知
  • Swift 无法将表达式的类型“Void”转换为类型“String!”

    我正在尝试使用一段示例代码这篇 NSHipster 文章 http nshipster com ios8 大约在页面的中间位置 var inputStream NSInputStream var outputStream NSOutputS
  • 在 SwiftUI 中使用获取视图的宽度

    我需要获取渲染视图的宽度SwiftUI 这显然没那么容易 我的看法是 我需要一个返回视图尺寸的函数 就这么简单 var body some View VStack alignment leading Text timer name font
  • 如何在 RealityKit 中录制视频?

    我在 Xcode 中有一个 RealityKit 项目 我想记录ARView 我考虑过ReplayKit 但那是为了屏幕录制 我只想录制ARView与它的相机饲料 我考虑过 AFathi 的开源项目 ARVideoKit 但它不支持 Rea
  • 检查url图片是否存在

    我正在尝试使用 if 语句检查 url 图像是否存在 然而 当尝试通过错误的图像网址测试它时 它会不断返回 致命错误 在解包可选值时意外发现 nil code var httpUrl subJson image url stringValu
  • 在从初始化器返回 nil 之前,必须初始化类实例的所有存储属性

    尽管我不断收到上述消息 但我正在尝试在课堂上使用此代码 let filePath NSString let fileHandle NSFileHandle let totalFileLength CUnsignedLongLong init
  • 在 DecodingError 中采用 CustomNSError

    我正在使用 Crashlytics 编写一个错误记录器 并且遇到了一个问题 这个问题让我质疑我对协议和动态调度的理解 使用 Crashlytics 记录非致命错误时 API 需要一个符合错误的对象和一个可选的用户信息字典 我现在正在查看 J
  • 查询链接到 GeoFire 的 firebase 数据

    读完这些问题后 将 Geofire 位置与 Firebase 条目关联 https stackoverflow com questions 33885733 associate geofire location with firebase
  • 关于将 Objective C 代码添加到 swift 动态框架的澄清

    我有一个 swift 动态框架 当前正在链接到另一个用 Objective C 编写的框架 这可以工作 但很烦人 因为 Objective C 框架实际上只有 2 个文件 我想知道是否有办法将其带入我的 swift框架 如果这是我会使用的应
  • 如何在 Swift Joint 中创建自定义链?

    我正在尝试创建一个LocationManager组合的包装 我有一个发布者和一些触发发布者的函数 但是 我想将它们与自定义命令组合在一起 这是我到目前为止得到的 available OSX 10 15 iOS 13 tvOS 13 watc
  • 在 Swift 2.0 中以横向模式使用 UIImagePickerController

    我正在编写一个仅限 LandScape 的 iPad 应用程序 我需要从库中拍照以发送数据库 但图像上传屏幕仅适用于纵向模式 如何将其更改为横向模式 我读过一些关于 UIPickerControllerDelegate 不支持横向模式的内容
  • 在 Pages 文稿中打开文本—Swift

    在我的 Swift 2 应用程序中 用户通过文本字段创建一串文本 然后将其共享给另一个应用程序 现在 我只能将文本共享为 txt 文件 这不提供选项Open In Pages当我打开系统共享对话框时 如何才能让用户可以选择将输入的文本作为
  • supportedInterfaceOrientations 方法不会重写其超类中的任何方法

    在 UIViewController 中 这段代码 public override func supportedInterfaceOrientations gt UIInterfaceOrientationMask if let mainC
  • 如何使用逗号和行分隔符对字符串进行标记

    我正在 Swift 中制作一个简单的 String Tokenizer 就像在 Java 中一样 但这对我来说确实不起作用 我的数据源中每行的末尾用 分隔 数据用逗号分隔 例如 字符串 1 字符串 2 字符串 3 字符串 1 字符串 2 字
  • 上下文菜单未在 SwiftUI 中更新

    我正在尝试设置 SwiftUI contextMenu带有一个切换按钮Bool价值 上下文菜单的按钮文本应该在以下情况下更改 Bool切换 但上下文菜单不会更新 有没有办法强制更新上下文菜单 描述问题的示例代码 import SwiftUI
  • 从字典创建 Swift 对象

    如何根据 Swift 字典中的查找值动态实例化类型 希望这对其他人有用 我们需要进行一些研究才能弄清楚这一点 目标是避免巨大的 if 或 switch 语句从值创建每个对象类型的反模式 class NamedItem CustomStrin
  • 使用未声明的类型“对象”

    这太奇怪了 通常我可以理解未声明的类 但这是声称 Object 类本身未声明 NSObject 可以工作 但我的项目设置方式我需要它是一个纯 Swift 对象 我的类标题如下所示 import UIKit import Foundation
  • Facebook 登录打开错误的应用程序

    我正在尝试使用 facebook 实现应用程序的登录 但每次我尝试登录时 它都建议打开错误的应用程序 我尝试了一些在这里找到的东西 但没有成功 在 Facebook 的开发者页面上我添加了一个后缀 我的 plist 如下 有谁知道发生了什么
  • 如何在 SwiftUI 中延迟动画?

    我想为两个文本字段设置动画 第二个字段有延迟 但它不起作用 没有延迟 它们同时从位置 100 动画到 0 这是代码 State private var offset CGFloat 100 State private var offset2

随机推荐