【问题标题】:Swift: Enumate between tableView sections and rowSwift:在 tableView 部分和行之间枚举
【发布时间】:2019-06-06 12:24:21
【问题描述】:

我想在 tableView 中选择一行。 但是

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    switch indexPath.section {
        case 0:
            switch indexPath.row {
                case 0:
                    ...
            }
        ...
}

这个我想迭代

private enum Section {
    case section0
    case section1
    ...
}

private enum Section0 {
    case section0row0
    case section0row1
    ...
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    switch Section(rawValue: indexPath.section)! {
        case .section0:
            switch Section0(rawValue: indexPath.row)! {
                case section0row0:
                    ...
            }
        ...
}

像这样。

也许有更好的方法来编码枚举... 有人能告诉我一个非常聪明的解决方案吗?

谢谢:)

【问题讨论】:

  • 你先告诉我们你的用例怎么样 - 你到底想做什么?肯定有比你正在做的更好的方法。
  • 同意 mag_zbc,你应该给我们一个上下文来理解哪个是最好的解决方案。例如,您的主要目标是什么?您的表格视图是静态的还是动态的?您的数据源是如何构建的?
  • 对节使用枚举是可以的。对于行,它有点令人困惑。为什么要硬编码要处理的行数?如果您的所有内容都是硬编码的,只需在情节提要中进行,而无需完全编写代码!

标签: ios swift enums tableview


【解决方案1】:

有很多方法可以解决这个问题,其中最简单但不是最好的方法之一是一系列操作

例如:

import UIKit
import Foundation

typealias closure = ()->()

extension Collection {

    subscript (safe index: Index) -> Element? {
        return indices.contains(index) ? self[index] : nil
    }
}


struct ListOfAction {

    private var list: Array<Array<closure>>

    init() {
        self.list = [[]]
    }

    mutating func append(_ at: IndexPath,method:@escaping closure) {
        self.list[at.section].append(method)
    }

    mutating func insert(_ at: IndexPath,method:@escaping closure) {
        self.list[at.section].insert(method, at: at.row)
    }

    func call(at:IndexPath) {
        self.list[safe: at.section]?[safe: at.row]?()
    }

    func getClosure(at: IndexPath) -> closure? {
        return self.list[safe: at.section]?[safe: at.row]
    }
}


var listOfAction = ListOfAction()
var idx = IndexPath(row: 0, section: 0)
listOfAction.append(idx) {
    print("hello World")
}

listOfAction.insert(IndexPath(row: 1, section: 0)) {
    print("bye World")
}

listOfAction.call(at: IndexPath(row: 1, section: 0))
listOfAction.getClosure(at: idx)?()

注意:首先你应该关心索引的安全性; 其次,您应该根据您的要求修改答案以变得不可变或其他任何东西。 更好的方法是使用泛型方法。

【讨论】:

  • 您是否尝试过运行您的代码?我猜不是,因为它会因Index out of range 错误而崩溃
  • @mag_zbc,你导入 UIKit 了吗?另外,请阅读注释部分 :-) 代码工作正常你应该在构建表格视图并调用你的方法 onAction 时尝试这个,好的部分是它更容易在 Rx 中使用
  • 您认为当您在append 函数中为空数组下标时会发生什么?另外,如果没有使用单个 UIKit 类,我为什么要导入 UIKit
  • @mag_zbc 阅读此部分:首先,您应该关心索引的安全性,例如:下标(安全索引:索引)-> 元素? { 返回索引。包含(索引)?自我[索引]:无 }
  • @mag_zbc 带有行和部分初始化器的 IndexPath 在 UIkit 中,它不在基础中:-)
猜你喜欢
  • 2013-10-27
  • 1970-01-01
  • 2016-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-04
相关资源
最近更新 更多