我在我的 iOS 应用程序中使用 MoPub 在 UITableView
中显示原生广告。我遇到了一个问题,我遇到了 fatal error: Array index out of range
错误,我明白为什么,但我不知道如何解决它。
MoPub 将行插入到 UITableView
中,因此 editActionsForRowAtIndexPath
的 indexPath
参数包括包含广告的行。但是,表的数据数组不包括这些行,因此对于插入的每个广告,与数据数组中的索引相比,显示数据的行的 indexPath
为 +1对于那一行。请参阅下面的 editActionsForRowAtIndexPath
方法。
override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
// fetch the data for the currently selected row
let currentDictionary = xmlParser.arrParsedData[indexPath.row] as Dictionary<String, String>
self.shareURL = currentDictionary["link"]!
var shareAction = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "Share" , handler: {
(action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
NSLog("indexPath:%d", indexPath.row)
})
return [shareAction]
}
例如,如果我在第三行(索引 = 2)有一个广告,在非 MoPub 广告行上滑动,我会得到以下输出:
索引路径:0
索引路径:1
索引路径:3
索引路径:4
所以 MoPub 广告被计算在 indexPath 参数中,但由于该行不存在于我的 tableView 数据源数组中,indexPath 参数现在不同步。
如何确保数据数组的索引和表的行保持同步?
最佳答案
您可以在 editActionsForRowAtIndexPath 中获取当前 indexPath 处的单元格。使用此单元格,我们可以获得适当的 indexPath,而无需使用 mp_indexPathForCell 包含广告索引。
由于 editActionsForRowAtIndexPath 接受了 IndexPath,当包含广告时它是不一样的,我们必须有办法将 indexPath 编辑为正确的参数。
let cell = cellForRowAtIndexPath(indexPath)
let indexPath = mp_indexPathForCell(cell)
以上代码将 indexPath 替换为修改后的 indexPath,不包含广告索引。
关于ios - 在 iOS 上将 editActionsForRowAtIndexPath 与 MoPub 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31367635/