ios - 如何在Swift中显示数组列表对应的图像

标签 ios arrays swift

在下面的代码中,我使用图像文件名列表初始化了 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/

相关文章:

arrays - VBA:数组项可以在数组本身内拆分吗?尝试给出 "Type Mismatch"错误

arrays - 排序数组和对应数组

ios - 在 PayPal 中启用信用卡付款会导致模拟器和物理设备崩溃

ios - 如何从 Firebase 的 iOS API 获取服务器时间戳?

ios - 执行选择器上的 EXC_BAD_INSTRUCTION

arrays - 如何将结果保存为索引数组?

c++ - 为什么 a[] 和 *a 的行为不同?

ios - swift 在 Iphone 上的屏幕截图只有白色背景

ios - 从自定义 uitableview 单元格获取 uitextfield 数据 - Swift

swift - 我想从 Storyboard 移动到另一个 Storyboard ,它基本上是一个标签栏 Controller