我在菜单中做了两部分的幻灯片,并将所有案例写在一个枚举中。 我知道每个部分都从索引0开始,并且不同部分中的每个项目都将获得相同的值。
enum MenuType: Int {
//section 1
case plan
case documentation
case visitlist
case document
case constructdiary
case plancorrection
//section 2
case sync
case settings
case info }
class MenuViewController: UITableViewController {
@IBOutlet weak var imageView: UIImageView!
var didTapMenuType: ((MenuType) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
setupImageView()
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let menuType = MenuType(rawValue: indexPath.row) else { return }
dismiss(animated: true) { [weak self] in
self?.didTapMenuType?(menuType)
}
}
private func setupImageView() {
imageView.frame = CGRect(x: 0, y: 0, width: 35, height: 35)
}
}
是否可以编辑代码,以使案例.sync与案例中的.plan具有不同的值?
答案 0 :(得分:1)
按如下所示将部分和行属性添加到枚举
enum MenuType: Int, CaseIterable, CustomStringConvertible {
//section 1
case plan, documentation, visitlist, document, constructdiary, plancorrection
//section 2
case sync, settings, info
var section: Int {
switch self {
case .plan,.documentation,.visitlist,.document,.constructdiary,.plancorrection: return 0
case .sync,.settings,.info: return 1
}
}
var row: Int? {
switch self.section {
case 0: return self.rawValue
case 1: return self.rawValue - MenuType.allCases.filter { $0.section < self.section }.count
default: return nil
}
}
var description: String {
switch self {
case .plan: return "plan"
case .documentation: return "documentation"
case .visitlist: return "visitlist"
case .document: return "document"
case .constructdiary: return "constructdiary"
case .plancorrection: return "plancorrection"
case .sync: return "sync"
case .settings: return "settings"
case .info: return "info"
}
}
}
您可以通过比较indexPath部分和行来获得选定的菜单类型
class MenuViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
}
override func numberOfSections(in tableView: UITableView) -> Int {
return Array(Set(MenuType.allCases.map { $0.section })).count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return MenuType.allCases.filter{ $0.section == section }.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")//tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let type = MenuType.allCases.first(where: { $0.section == indexPath.section && $0.row == indexPath.row })
cell.textLabel?.text = type?.description
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedMenuType = MenuType.allCases.first(where: { $0.section == indexPath.section && $0.row == indexPath.row })
}
}