来自数组索引的表视图超出范围
Posted
技术标签:
【中文标题】来自数组索引的表视图超出范围【英文标题】:Table view from array index out of range 【发布时间】:2015-12-07 17:36:20 【问题描述】:我正在使用数组从数据库中读取数据,目前我在数组中有 8 个项目。我正在尝试制作一个有节标题的表格。目前我有 4 个部分,我已经正确设置它并且它可以工作。它也可以第一次运行,但是当我尝试向后滚动时,索引超出了范围。我正在使用 myarray[myindex] 为每个项目设置单元格数据,但这不起作用。
看来我需要将我的数据分成 4 个部分,每个部分只包含每个部分的数据,以让表格视图正确控制它。数据可以包含任意数量的部分。
有没有更好的方法来做到这一点?
我附上了一张图片来描述这个问题。
谢谢
根据要求添加代码。
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
// #warning Incomplete implementation, return the number of sections
print("Returning Sections - > \(sections)")
return sections //seems to work
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
// #warning Incomplete implementation, return the number of rows
print("Return number of rows in section -> \(noRowsInSection[section])")
return noRowsInSection[section] // seems to work
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
return sectionHeader[section] // seems to work
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
// Format for section Headers
let header:UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.textLabel!.textColor = UIColor.blueColor()
UIColor.blueColor()
header.textLabel!.font = UIFont.boldSystemFontOfSize(12)
header.textLabel!.frame = header.frame
header.textLabel!.textAlignment = NSTextAlignment.Right
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCellWithIdentifier("OurCell", forIndexPath: indexPath) as! OurTableViewCell
print("myindex - > \(myindex) row -> \(indexPath.row)")
cell.OurCellLabel.text = MyHouses[myindex].getAddressDetails() // End configure houses.cell
//cell.OurCellLabel.text = MyHouses[indexPath.row].getAddressDetails() // End configure houses.cell
myindex++ // PROBLEM HERE - GOES OUT OF RANGE
return cell
这里我从 sqlite DB 获取数据
func GetListOfHousesFromDB()
let docsDir = dirPaths[0]
let databasePath = docsDir.stringByAppendingString("/newdb.db")
if fileMgr.fileExistsAtPath(databasePath as String)
let houseDB = FMDatabase(path: databasePath as String)
if houseDB.open()
var noRows: Int = 0
var sql = "select count(Address) as cnt from Houses" // Define Query
houseDB.executeStatements(sql) // Execute Query
let results:FMResultSet? = houseDB.executeQuery(sql,withArgumentsInArray: nil) //Get results from Query
if results?.next() == true
let cnt = (results?.stringForColumn("cnt"))! // Retrieve number of rows from DB
noRows = Int(cnt)!
var i = 0
sql = "SELECT Address, Street, City, State, Zip from Houses ORDER BY State, City, Street, Address" // Define Query
houseDB.executeStatements(sql) // Execute Query
let results2:FMResultSet? = houseDB.executeQuery(sql,withArgumentsInArray: nil) // Get results from Query
while results2?.next() == true
MyHouses.append(newhouse())
MyHouses[i].address = (results2?.stringForColumn("Address"))!
MyHouses[i].street = (results2?.stringForColumn("Street"))!
MyHouses[i].city = (results2?.stringForColumn("City"))!
MyHouses[i].state = (results2?.stringForColumn("State"))!
MyHouses[i].zip = (results2?.stringForColumn("Zip"))!
print("Address -> \(i) \(MyHouses[i].getAddressDetails())")
i++
houseDB.close()
【问题讨论】:
向我们展示一些相关代码,尤其是cellForRowAtIndexPath
、numberOfRowsInSection
和numberOfSectionsInTableview
方法
【参考方案1】:
基于您的另一个post,您需要更新的House
模型和更新的数据结构来处理表格视图的数据。
房屋 - 模型类
struct House
var address: String
var street: String
var city: String
var state: String
var zip: String
func getAddressDetails() -> String
return "\(address) \(street) \(city) \(state) \(zip)"
func getCityState() -> String
return "\(city) - \(state)"
加载数据的帮助类
class HouseDataHelper
private static let _sharedInstance = HouseDataHelper()
var myHouses: Dictionary<String, [House]> = [:]
private init()
loadHouseData()
static func sharedInstance() -> HouseDataHelper
return _sharedInstance
private func loadHouseData()
var houses = [House]()
//Populating your actual values here. GetListOfHousesFromDB()
//Loading dummy data for testing
var sectionHeader = ""
for i in 0...4
sectionHeader = "Header \(i)"
houses += [House(address: "Address1", street: "Street1", city: "City1", state: "State1", zip: "Zip1")]
houses += [House(address: "Address2", street: "Street2", city: "City2", state: "State2", zip: "Zip2")]
houses += [House(address: "Address3", street: "Street3", city: "City3", state: "State3", zip: "Zip3")]
houses += [House(address: "Address4", street: "Street4", city: "City4", state: "State4", zip: "Zip4")]
houses += [House(address: "Address5", street: "Street5", city: "City5", state: "State5", zip: "Zip5")]
myHouses.updateValue(houses, forKey: sectionHeader)
houses = []
表格视图控制器
class TableViewController: UITableViewController
var houses = HouseDataHelper.sharedInstance().myHouses
var sectionHeaders: [String] = []
override func viewWillAppear(animated: Bool)
super.viewWillAppear(animated)
sectionHeaders = Array(houses.keys.sort())
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
return houses.count
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
if let rows = houses[sectionHeaders[section]]
return rows.count
return 0
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
return sectionHeaders[section]
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
//Populate cells based on "houses"
【讨论】:
我会试一试,有些东西我不太明白,但我们会看看我能不能让它工作......谢谢! 我最终使用了一个多维数组[section][row]。它正在工作。以上是关于来自数组索引的表视图超出范围的主要内容,如果未能解决你的问题,请参考以下文章
从数组中删除 - 致命错误:索引超出范围 - SwiftUI 绑定