我的應用程式中有幾個表視圖,它們使用一個名為TaskListDataSource類的資料源實體,該資料源符合UITableViewDataSource
class TaskListDataSource。NSObject {
typealias TaskCompletedAction = () -> Void
private var tasks: [Task] = SampleData.tasks.
private var taskCompletedAction: TaskCompletedAction?
init(taskCompletedAction: @escaping TaskCompletedAction) {
self.taskCompletedAction = taskCompletedAction
super.init()
}
}
extension TaskListDataSource。UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasks.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView. dequeueReusableCell(withIdentifier: "taskCell", for: indexPath) as? TaskCell else {
fatalError("Unable to dequeue TaskCell"/span>)
}
cell.configure(task: tasks[indexPath.row]) {
self.tasks[indexPath.row].completed.toggle()
self.taskCompletedAction?/span>()
}
return cell
}
}
我通過依賴注入傳入實體,并像這樣設定表視圖資料源。我對所有使用該資料源物件的視圖控制器都這樣做。
var taskListDataSource: 任務串列資料源。
init?(coder: NSCoder, taskListDataSource: TaskListDataSource) {
self.taskListDataSource = taskListDataSource
super.init(coder: coder)
}
required init? (coder: NSCoder) {
fatalError("init(coder:) has not been implemented"/span>)
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "TaskCell", bundle: nil),forCellReuseIdentifier。"taskCell")
tableView.dataSource = taskListDataSource
}
但是我想實作一種方法,使其中一個UITableViewControllers的行數被限制在3行。目前,由于下面的代碼片段,它總是只顯示任務陣列中的總任務量。
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tasks.count
}
在每個表視圖上,它顯示了任務的總量,但我希望有一種方法,可以在某種程度上保持cellForRowAt函式的可重用性,但使numberOfRows函式動態化。
uj5u.com熱心網友回復:
你可以添加一個字典來保存每個表視圖的限制
...
private maxRows。[String: Int?] = [ :]
...
添加一個函式來處理系結的資料源
...
func add(_ tableView: UITableView, maxRows: Int? = nil) {
if let id = tableView.id {
self.maxRows[id] = maxRows
}
tableView.datasource = self.
}
...
然后,datasoure函式numberOfRowsInSection成為
。func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let id = tableView.id {
return maxRows[id] ? tasks.count
}
return tasks.count
}
并且像這樣設定表視圖的資料源
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "TaskCell", bundle: nil),forCellReuseIdentifier。"taskCell")
taskListDataSource.add(tableView, maxRow: 3)
}
tableView.id可以是你想要的任何東西。例如:你子類化UITableView并添加一個屬性
class UITableViewWithID。UITableView {
var id: String?
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/311713.html
標籤:
