【问题标题】:Adding Image to UITableView in Swift 2.0在 Swift 2.0 中将图像添加到 UITableView
【发布时间】:2015-11-10 20:39:19
【问题描述】:

我有一个带有自定义原型单元的UITableView,它是超类UITableView 的子类。我正在尝试使用NSMutableArray 将多张照片添加到表格中:

这是我的代码:

let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! PillarTableViewCell



cell.titleLabel.text = self.objects.objectAtIndex(row) as? String

        cell.pillarIcon.image = self.imageObjects.objectAtIndex(row) as? UIImage

生成的每一行都有一个label 和一个imageIcon。我从来没有向UITableView 添加图像,上面的代码和我来的一样接近。我收到的错误是

由于未捕获的异常“NSRangeException”而终止应用程序,原因:“*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]”

这个错误让我认为它不会根据我编写的代码将事情放在一行中。它是否正确?

我该如何解决这个问题。 谢谢。

根据要求,这里是numberOfRowsInSection 部分:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return objects.count + staticObjects.count
    }

【问题讨论】:

  • ok..请检查您是否在“cellForRowAtIndexPath”和“numberOfRowsInSections”中传递了相同的数组。似乎数组在索引处没有值,当您传递不同的数组时会发生这种情况。
  • 所以,IDK 你在哪一行崩溃,但是当你尝试访问它时,错误告诉你 self.objects 或 self.imageObjects 中的东西少于 2 个。如果你在一个不存在的索引处向一个数组请求一个对象,它会崩溃。
  • 为什么是row 而不是indexPath.row
  • 你能把 numberOfRowsInSections 的代码也贴出来吗?
  • @dpstart 很抱歉长时间的延迟有一些事情需要处理。 row 而不是 indexPath.row 的原因是我有两个原型单元。一个只有一个对象,第二个有多个可以增加或减少的对象。所以我必须做数学并创建一个变量来保存index

标签: ios swift uitableview cocoa-touch swift2


【解决方案1】:

我认为您的问题是您的UITableView 中的部分数高于您的对象数组中的索引数。 尝试在 numberOfRowsInSection 函数中添加条件子句。

     var row = Int;
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            var count = 0;
            if (row == 0){ //UITableView index starts at 0
           count = staticObjects.count
           }
            else{
           count = objects.count    
           } 
      return count;      

}

        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
           let row = indexPath.row;
    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! PillarTableViewCell
    cell.titleLabel.text = self.objects[indexPath.row] // or use row doesn't matter
   cell.pillarIcon.image = self.imageObjects.objectAtIndex(row) as? UIImage
   return cell;
}

【讨论】:

    猜你喜欢
    • 2011-06-27
    • 2015-05-23
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    相关资源
    最近更新 更多