我有一个应用,该应用使用从api调用接收到的一些属性填充uitableview
。因此,我的问题是我如何才能使第一个cell
例如具有名称“ Back”和一些图像,然后再使用从api调用接收的属性填充其他cells
?如果有人可以发表一些例子,那就太棒了。
答案 0 :(得分:1)
您可以尝试
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "CellId")
switch indexPath.row {
case 0:
cell.textLabel!.text = "back"
cell.imageView?.image = UIImage(named: "back.png")
break
default:
cell.textLabel!.text = array[indexPath.row - 1]
break
}
retun cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrayCount + 1
}
答案 1 :(得分:0)
Maybe what you want is not a first cell that can be scrolled out together with the other cells, but a header that stays at its place while the other cells scroll. If this is the case, you could use:
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Section \(section)"
}
This creates a simple text header.
If you want to use a custom header, you had to define a header view:
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView() // Here you had to use a view that you set up earlier
return view
}
These headers can be created for every section of your table.
EDIT:
I implemented a simple tableView project, and added the code provided by Simke in his/her comments.
import Foundation
import UIKit
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = "Title"
return cell
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let vw = UIView()
vw.frame.size.height = 40
let btnBk = UIButton(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: vw.frame.height))
btnBk.backgroundColor = .blue
btnBk.setTitle("back", for: .normal)
btnBk.addTarget(self, action: #selector(btnAct), for: .touchUpInside)
vw.addSubview(btnBk)
return vw
}
@objc func btnAct(sender: UIButton!){
print("a")
}
}
Here, the button in the header view works, i.e. "a" is printed in the logs.
答案 2 :(得分:0)
首先将表格视图分为两部分。
第0节:在此处出队您的自定义必需单元格。
第1部分:在此处使用来自API的数据来缓存自定义单元格。
代码示例:
extension ProjectDetailViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
//deque your cell you want to place before data from API
case 1:
//deque data from api here
case default:
break
}
}
注意:请记住从API获取数据后重新加载表格视图