【发布时间】:2016-03-28 10:35:08
【问题描述】:
我想展示我库中的 25 首歌曲。这是我的代码:
var allSongsArray: [MPMediaItem] = []
let songsQuery = MPMediaQuery.songsQuery()
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 25 //allSongsArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell")
let items = allSongsArray[indexPath.row]
cell?.textLabel?.text = items.title
cell?.detailTextLabel?.text = items.artist
cell?.imageView?.image = items.artwork?.imageWithSize(imageSize)
return cell!
}
当我运行它时,它崩溃了,因为:
致命错误:索引超出范围
我尝试将numberOfRowsInSection 更改为allSongsArray.count,但最终出现相同的错误。
【问题讨论】:
-
您绝对应该返回
allSongsArray.count而不是文字数字;在查询执行之前,数组将包含 0 个项目。发生异常时您尝试访问的索引是什么? -
它肯定会以 25 硬编码为行数而崩溃,因为您的数组被声明为空。我怀疑它会与
allSongsArray.count崩溃,但它不会显示任何东西...... -
哦,是的,你是对的。它不显示任何东西。如何显示 25 首歌曲? @Grimxn
-
将
MPMediaItem对象添加(追加)到allSongsArray并重新加载表格视图
标签: ios swift uitableview