#42Table View 的基本功能
表格的基本功能/UITableViewDataSource 的 function/WebKit
Published in
5 min readMay 11, 2021
📌建立新的UITableViewController
📌不固定行數的表格內容
📌自訂型別
📌建立Array
📌有幾個Section/每個Section有幾個 cell
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//回傳數量
return Songs.count
}
📌設定 cell 的 Identifier
📌cell id 定義成常數
struct PropertyKeys {
static let songCell = “songCell”
}
📌建立新的UITableViewCell並建立@IBOutlet
📌要顯示的 cell內容(利用 as? 轉型成 cell 的型別)
//UITableViewCell
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//轉型
//as?
guard let cell = tableView.dequeueReusableCell(withIdentifier: PropertyKeys.songCell, for: indexPath) as? SongTableViewCell else { return UITableViewCell() }
let song = Songs[indexPath.row]
//設定標題
cell.nameLabel.text = song.name
//設定介紹
cell.introLabel.text = song.intro
//設定圖片
cell.showImg.image = UIImage(named: song.imgName)
return cell
}
📌建立ViewController
📌傳到下一頁開啟網址
- DetailViewController
init?(coder:NSCoder,song:Song){
self.song = song
super.init(coder: coder)
}required init?(coder: NSCoder) {
fatalError(“init(coder:) has not been implemented”)
}
- SongTableViewController
@IBSegueAction func showDetail(_ coder: NSCoder) -> DetailViewController? {
guard let row = tableView.indexPathForSelectedRow?.row else { return nil }return DetailViewController(coder: coder, song: Songs[row])
}
📌點開cell下一頁顯示的內容
override func viewDidLoad() {
super.viewDidLoad()
if let url = URL(string: song.songUrl){
let request = URLRequest(url: url)
songWebView.load(request)
}
}
📌如果表格不要有分隔線的話