在下面的代码中,我使用图像文件名列表初始化了 Images
数组。我希望图像的顺序与 Names
数组的顺序对齐。这就是我尝试的方法,但出现错误:
Thread 1: EXC_BAD_INSTRUCTION ( code=EXC_I386_INVOP, subcode = 0x0)
The console output: fatal error: Array index out of range (lldb)
代码
class NonameTableViewController: UITableViewController {
var Names = [" Ferro", "Korean", "HUH?","CatCafe", "UINITY", "FAKESTORE" ,"IRANOUTOFNAMES", "OKAY", "KEEP CODING"]
var Images = ["cafedeadend.jpg", "homei.jpg", "teakha.jpg", "cafelois1.jpg"," petiteoyster.jpg", "forkeerestaurant.jpg"]
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIndentifier = "Cell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIndentifier, forIndexPath: indexPath)
//configure cell
cell.textLabel?.text = Names[indexPath.row]
cell.imageView?.image = UIImage(named: Images[indexPath.row])
return cell
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return Names.count
}
最佳答案
只需更改您的 numberOfRowsInSection
函数即可:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return min(Names.count, Images.count)
}
这将确保您只显示您拥有名称和图像的图像的图像/名称。
关于ios - 如何在Swift中显示数组列表对应的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34327150/