我的場景是我有三種不同型別的陣列,它們可能包含也可能不包含值。我的 tableview 有 3 個部分,其中包含部分標題。我無法找到動態設定部分的解決方案,即,如果我的一個陣列沒有值,那么我不想顯示該部分。如果 3 個陣列具有值,則顯示 3 個部分,或者如果任何一個陣列沒有值,則我不想顯示該部分。
uj5u.com熱心網友回復:
您的 numberOfSections 將是陣列的數量。numberOfRowsInSection 將是 tableViewDataSource 中該部分的每個陣列的計數。
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return array1.count
} else if section == 1 {
return array2.count
} else {
return array3.count
}
}
如果陣列中沒有專案,則該部分的行將為零。
uj5u.com熱心網友回復:
你可以做這樣的事情
// Create enum for simplifying the implementation.
enum SectionType{
case type1
case type2
case type3
}
class TestVC: UIViewController {
// create to show sections only when data is available
var sections: [SectionType] = []
// create you array types
var array1 = [String]()
var array2 = [String]()
var array3 = [String]()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
// Add enums to section only when array has some value
// You can do this when you get API data
if array1.count > 0{
sections.append(.type1)
}
if array2.count > 0{
sections.append(.type2)
}
if array3.count > 0{
sections.append(.type3)
}
}
}
extension TestVC: UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
// only those sections with data wil be visible
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch sections[section]{
case .type1:
return array1.count
case .type2:
return array2.count
case .type3:
return array3.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch sections[indexPath.section]{
// return different type of cells if required accourding to the data in array
case .type1, .type2, .type3:
return UITableViewCell()
}
}
}
uj5u.com熱心網友回復:
如果陣列可以動態更改(在加載視圖之后),您可以實作多個部分,如下所示:
func numberOfSections(in tableView: UITableView) -> Int {
var numberOfSections = 0
if array1.count > 0 { numberOfSections }
if array2.count > 0 { numberOfSections }
if array3.count > 0 { numberOfSections }
return numberOfSections
}
uj5u.com熱心網友回復:
您的資料源應如下所示 -sectionModels = [[cellModels]]
外部陣串列示部分的數量,內部陣串列示該部分中的單元格數量。
func numberOfSections(in tableView: UITableView) -> Int {
return sectionModels.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sectionModels[section].count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellModel = sectionModels[indexPath.section][indexPath.row]
// Configure UITableViewCell with cellModel
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/388634.html
上一篇:我們如何在Windows批處理檔案中用上個月的最后一天重命名檔案?
下一篇:Swift制作心愿單功能
