ในการเพิ่มปุ่มส่งที่ส่วนท้ายของมุมมองตาราง เราสามารถใช้ประโยชน์จากส่วนท้ายของมุมมองตารางได้ มาดูสิ่งนี้ด้วยความช่วยเหลือของตัวอย่างที่เราจะเพิ่มมุมมองส่วนท้ายให้กับตารางของเรา และภายในตาราง เราจะเพิ่มโค้ดสำหรับการเพิ่มปุ่มที่ด้านล่างของมุมมองตาราง
สร้างโปรเจ็กต์ใหม่ก่อน จากนั้นใน view controller ให้เพิ่มโค้ดต่อไปนี้ซึ่งจะเริ่มต้นตาราง เพิ่มส่วนและสองสามแถวลงในตาราง
func initTableView() {
let tableView = UITableView()
tableView.frame = self.view.frame
tableView.dataSource = self
tableView.delegate = self
tableView.backgroundColor = colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(tableView)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
cell?.layer.backgroundColor = colorLiteral(red: 0.2392156869, green:
0.6745098233, blue: 0.9686274529, alpha: 1)
cell?.textLabel?.text = "cell at \(indexPath.row)"
return cell!
} ตอนนี้ เรียกใช้ฟังก์ชันแรก initTableView() ในมุมมองทำการโหลดหรือวิธีการ viewDidAppear ของตัวควบคุมการดูของคุณ
ตอนนี้ให้เพิ่มโค้ดต่อไปนี้ซึ่งจะบอกให้ตารางกำหนดความสูงให้กับแถวและส่วนท้ายของตาราง
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 100
} ตรวจสอบให้แน่ใจว่าคุณได้ยืนยันคลาสของคุณเป็น UITableViewDataSource และ UITableViewDelegate มิฉะนั้น วิธีการเหล่านี้ด้านบนจะปรากฏเป็นข้อผิดพลาด
ตอนนี้ มาเพิ่มมุมมองส่วนท้ายและปุ่มในมุมมองส่วนท้าย
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerView = UIView()
footerView.backgroundColor = colorLiteral(red: 0.9686274529, green:
0.78039217, blue: 0.3450980484, alpha: 1)
footerView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height:
100)
let button = UIButton()
button.frame = CGRect(x: 20, y: 10, width: 300, height: 50)
button.setTitle("CustomButton", for: .normal)
button.setTitleColor( colorLiteral(red: 0, green: 0, blue: 0, alpha: 1), for: .normal)
button.backgroundColor = colorLiteral(red: 0.721568644, green:
0.8862745166, blue: 0.5921568871, alpha: 1)
footerView.addSubview(button)
return footerView
} เมื่อเราเรียกใช้โค้ดด้านบนบนอุปกรณ์ของเรา ด้านล่างนี้คือผลลัพธ์ที่ได้ คุณสามารถเพิ่มการดำเนินการที่กำหนดเองให้กับปุ่มและปรับแต่งได้ตามความต้องการ
