我有一个显示举重名称列表的 UITableViewController(想想举重),它用于两种不同的用途。可以从 View A 访问它以选择将保存为用户默认值的电梯。也可以从 View B 访问它以选择电梯,然后过滤电梯事件列表。在每种情况下,我都希望相应单元格上的复选标记指示当前默认提升(如果来自 View A)和相应单元格上的复选标记以指示当前选定的过滤器(如果来自 View B)。
我为表格单元格创建了一个 View 模型:
struct LiftCellViewModel: SelectionsRepresentable {
let liftName: String!
let liftsDictionary: [String: String]!
var text: String {
return liftName
}
var accessoryType: UITableViewCellAccessoryType {
let defaultLiftUuid = UserDefaults.lift()
let defaultLiftName = liftsDictionary[defaultLiftUuid]
if liftName == defaultLiftName {
return .checkmark
} else {
return .none
}
}
}
这非常有效,但只能处理其中一种情况(来自 View A)。因此,为了尝试让它也适用于其他场景(来自 View B),如果列表用于选择过滤器并在 switch 语句中使用它来确定要采取的路径,我将传递一个 bool为了设置复选标记:
let liftName: String!
let liftsDictionary: [String: String]!
let selectForFilter: Bool!
var text: String {
return liftName
}
var accessoryType: UITableViewCellAccessoryType {
switch selectForFilter {
case true:
let filterLiftUuid = UserDefaults.logFilterLiftUuid()
let filterLiftName = liftsDictionary[filterLiftUuid!]
if liftName == filterLiftName {
return .checkmark
} else {
return .none
}
case false:
let defaultLiftUuid = UserDefaults.lift()
let defaultLiftName = liftsDictionary[defaultLiftUuid]
if liftName == defaultLiftName {
return .checkmark
} else {
return .none
}
default:
return .none
}
}
此 View 用于创建 didSelectRow 中的每个单元格:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellViewModel: SelectionsRepresentable
let cell = tableView.dequeueReusableCell(withIdentifier: "liftCell", for: indexPath)
let lift = viewModel.fetchedResultsController?.object(at: indexPath) as! Lift
let liftName = lift.liftName
cellViewModel = LiftCellViewModel(liftName: liftName, liftsDictionary: liftsDictionary, selectForFilter: selectForFilter)
cell.textLabel?.text = cellViewModel.text
cell.accessoryType = cellViewModel.accessoryType
return cell
}
这行得通,但是 switch
语句似乎有很多代码来完成如此简单的事情。有没有更快捷的方法来做到这一点?
最佳答案
如果您查看您对 accessoryType
的定义,实际上唯一的区别是您检索的是哪个 UUID,因此这可以简化为如下所示:
var accessoryType: UITableViewCellAccessoryType {
let uuid = selectForFilter! ? UserDefaults.logFilterLiftUuid() : UserDefaults.lift()
return liftName == liftsDictionary[uuid!] ? .checkmark : .none
}
说到 swifty,您可能还需要重新考虑对隐式解包可选类型的大量使用,并尽可能使用非可选类型。
关于swift - 如何根据用于两个不同目的的 UITableViewController 中的不同条件设置 UITableViewAccessoryType?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43938508/