TableViewModel允许您在Swift中以声明方式创建UITableView实例。您可以在不担心实现UITableViewDelegate和UITableViewDataSource方法的情况下添加、插入或删除区域和行。
TableViewModel将不同类型的单元格注册为TableView中的可重用单元格,并使用可实现requests当需要它们时。从性能的角度来看,它并不比手动实现UITableViewDataSource有所不同。
TableViewModel受到DXTableViewModel的启发,但它并不是DXTableViewModel的Swift实现。它是从头开始用Swift编写的,并且做了很多事情。
要运行示例项目,克隆仓库,然后首先从示例目录中运行pod install
。
// Create TableViewModel
self.tableViewModel = TableViewModel(tableView:self.tableView)
// Create and add the section
let tableSection = TableSection()
tableSection.headerTitle = "Section title"
tableSection.headerHeight = 30
self.tableViewModel.addSection(tableSection)
// Create and add the row
let tableRow = TableRow(cellIdentifier:"MyCell") // Cell identifier is either the reuse identifier of a reusable cell, or name of an XIB file that contains one and only one UITableViewCell object
tableRow.userObject = "My tag" // Optional <AnyObject> property to identify the row later
tableSection.addRow(tableRow)
tableRow.configureCell {
cell in
let label = cell.viewWithTag(1) as! UILabel
label.text = "Custom text"
}
tableRow.onSelect {
row in
NSLog("selected row \(row.userObject)")
}
// Adding multiple rows
tableSection.addRows(arrayOfRows) // IMPORTANT: Notice that this performs much faster than inserting a bunch of rows one by one in a loop
// Insert a row at an index
tableSection.insertRow(newRow, atIndex:0)
// Remove a row
tableSection.removeRow(tableRow)
// Remove multiple rows
tableSection.removeRows(arrayOfRows) // IMPORTANT: Notice that this performs much faster than removing a bunch of rows one by one in a loop
// Removing all rows
tableSection.removeAllRows()
// Insert a section at an index
tableViewModel.insertSection(newSection, atIndex:0)
// Remove section
tableViewModel.removeSection(tableSection)
// Remove all sections
tableViewModel.removeAllSections()
tableRow.configureCell {
cell in
let myCustomCell = cell as! MyCustomCell
myCustomCell.setTitle("Custom title")
}
let customHeaderView = UIView() // Can be any UIView or subclass instance
tableSection.headerView = customHeaderView
tableSection.headerHeight = customHeaderView.frame.size.height
tableRow.height = Float(90)
tableRow.configureHeight {
return 100
}
tableSection.rowAnimation = UITableRowAnimation.Right
tableSection.addRow(newRow)
tableViewModel.sectionAnimation = UITableRowAnimation.Fade
tableViewModel.addSection(newSection)
TableViewModel 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile 中
pod "TableViewModel"
Tunca Bergmen,[email protected]
TableViewModel 在 MIT 许可协议下提供。有关更多信息,请查看 LICENSE 文件。