Swift : sử dụng tableview trong swift - ios
Bài này mình sẽ hướng dẫn các bạn tạo tableview và hiển thị dữ liệu trên tableview
1. Tạo project
-> sau đó đên file viewController
2. khai báo tableview :
- var table_view:UITableView!
- vào hàm viewDidload : khởi tạo và tạo vị trí hiển thị - kích thước :
- table_view = UITableView()
- table_view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: - self.view.frame.height)
-
self.view.addSubview(table_view) -> add table vào màn hình view
3. trong class ViewController ta kế thừa thêm các class :
- class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {}
- Khai báo thêm các hàm protocol của UITableViewDataSource
Hiển thị số dòng trên table mình fix cứng 10
- func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 10
}
Set Chiều rộng của row
- func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 40
}
Các dữ liệu sẽ được hiển thị trong hàm này hàm này trả về cell của table
- func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(frame: CGRect(x: 0, y: 0, width: self.table_view.frame.width, height:40))
cell.textLabel?.text = "đây là table view"
return cell
}
- Sau đó thêm 2 dòng vào trong viewDidload
- table_view.delegate = self
- table_view.dataSource = self
- Sau đó build project và xem thành quả
-> Cảm ơn các bạn đã theo dõi
Xem Video Huong Dan : https://youtu.be/U6XhH7RI5yY



Comments
Post a Comment