【发布时间】:2018-09-10 18:30:58
【问题描述】:
我有一个包含两个部分和四行的 UITableView。每个部分应该有两行内容。 除了这些项目在第 2 节中重复之外,一切正常:
但是,我想要这样:
我的代码如下:
斯威夫特 4
// structure for serverData type
struct serverData {
var structHosts: String
var structStatusImagesMain: String
var structServerStatusMain: String
}
填充单元格和部分的变量:
// data filled in my array "section" and in my array "myServerInfo" of type serverData
let sections = ["Section 1", "Section 2"]
let myServerInfo = [
serverData(structHosts: "www.google.com", structStatusImagesMain: "error", structServerStatusMain: "Error "),
serverData(structHosts: "www.amazon.com", structStatusImagesMain: "error", structServerStatusMain: "Error "),
serverData(structHosts: "www.ebay.com", structStatusImagesMain: "error", structServerStatusMain: "Error "),
serverData(structHosts: "www.apple.comt", structStatusImagesMain: "error", structServerStatusMain: "Error ")
]
这些是表格配置:
// table functions
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = serverStatusTable.dequeueReusableCell(withIdentifier: "serverStatusCell", for: indexPath)
let lblDescribtion : UILabel = cell.contentView.viewWithTag(6) as! UILabel
let lblServerStatus : UILabel = cell.contentView.viewWithTag(8) as! UILabel
let imgServer : UIImageView = cell.contentView.viewWithTag(7) as! UIImageView
if myServerInfo .isEmpty {
print("myServerInfo is empty: ", myServerInfo)
} else {
lblDescribtion.text = myServerInfo[indexPath.row].structHosts
imgServer.image = UIImage(named: myServerInfo[indexPath.row].structStatusImagesMain)
lblServerStatus.text = myServerInfo[indexPath.row].structServerStatusMain
}
return cell
}
【问题讨论】:
-
首先将您的数据模型组织成一个数组,与您希望它在表格视图中的显示方式相匹配。
-
重复输出是因为您没有考虑
indexPath的section属性。顺便说一句:viewWithTag已经过时了几年。在 IB 中设计一个自定义单元并使用 outlet。
标签: arrays swift uitableview sections