Delegate 練習 自定義tableView 使用UITableViewDelegate,UITableViewDataSource 音樂播放器[01]
Published in
5 min readAug 10, 2020
階段成果展示
最近蠻喜歡聽John Mayer “Where the Light Is ” Live 來做做看音樂播放器
之後想要增加評分機制儲存資料
歌曲資料部分
建立出歌曲的結構 包含
名稱, 歌手 ,專輯名, 圖片,評分
建立歌手 array名為 songs 這邊自訂方法 loadSong去新增
關於使用xib自定義tableviewCell
新增自定義cell newFile-Cocoa Touch Class-TableViewCell -XIB file 打勾
建立完cell 之後我們可以在MusicTable.xib中編輯所需要的元件 lable,image
cell 放上所需要label , image
連結到 MusicTableViewCell.swift
將id:命名MusicTableViewCell
將tableView 拉入 viewcontroller
將tableView連線到viewcontroller 並遵從UITableViewDelegate,UITableViewDataSource
將delegate設為 self(ViewController)
關於TableView使用xib
在viewDidLoad 註冊cell為自訂xib
self.tableview.register(UINib(nibName: "ChatLeftTableViewCell", bundle: nil), forCellReuseIdentifier: "chatLeftTableCell")
實現tableView 要實作兩個方法
numberOfRowInSection && cellForRowAt
numberOfRowInSection
回傳歌曲的數量
cellForRowAt
cell的部分指派cell為自訂xib
let cell=tableView.dequeueReusableCell(withIdentifier: "MusicTableViewCell", for: indexPath) as! MusicTableViewCell //指定cell 並轉型自訂TableViewCellcell.songImageView.image=UIImage(named: songs[indexPath.row].imageName) //修改Imagecell.singer.text=songs[indexPath.row].artistName //修改IBOutlet數值cell.songName.text=songs[indexPath.row].namecell.musicAlbum.text=songs[indexPath.row].albumNamecell.songRank.text="\(songs[indexPath.row].rating)"
程式碼
參考