我有一個2D數組,我想以特定模式在UITableView自定義單元格中填充。iOS Swift:在更新自定義UITableView單元格中的2D數組時獲得重複值
//從parse後臺檢索
var myArray = [["Name1", "Age1"],["Name2", "Age2"],["Name3", "Age3"]]
//我需要的是:
nameArray = ["Name1", "Name2", "Name3"]
ageArray = ["Age1", "Age2", "Age3]
所以,我可以用indexPath填補了自定義的UITableView細胞對於實例名稱的數據: nameArray [indexPath.row]
我嘗試使用用於循環,
var nameArray = NSMutableArray()
var ageArray = NSMutableArray()
//Inside CellForRowAtIndexPath
for data in myArray {
self.nameArray.addObject(data[0])
self.ageArray.addObject(data[1])
}
cell.nameLabel.text = "\(nameArray[indexPath.row])"
cell.ageLabel.text = "\(ageArray[indexPath.row])"
但是我在這兩個單元格中都得到了重複名稱和年齡標籤,並填充了Name1和Age1。有沒有人知道這是什麼錯?
有沒有更好的方法來根據需要重新加載這些數據?
//更新的完全工作代碼感謝@ l00phole誰幫我解決您要添加到nameArray
和ageArray
每次cellForRowAtIndexPath
問題
class NewViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView!
var data = [[String]]()
var cost = Double()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
uploadData()
}
func uploadData() {
let query = PFQuery(className:"Booking")
query.getObjectInBackgroundWithId("X0aRnKMAM2") {
(orders: PFObject?, error: NSError?) -> Void in
if error == nil && orders != nil {
self.data = (orders?.objectForKey("orderDetails"))! as! [[String]]
//[["Vicky","21"],["Luke", "18"],["7253.58"]]
//*****Removing the last element as it is not needed in the tableView data
let count = self.data.count - 1
let c = self.data.removeAtIndex(count)
cost = Double(c[0])!
//******
} else {
print(error)
}
self.reloadTableData()
}
}
func reloadTableData()
{
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
return
})
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:NewTableViewCell = self.tableView!.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! NewTableViewCell
// Configure the cell...
cell.nameLabel.text = "\(data[indexPath.row][0])"
cell.ageLabel.text = "\(data[indexPath.row][1])"
return cell
}
如何提取數據?您不是在索引路徑中調用行內單元格的獲取塊,是嗎? –
您是否在循環之前清除了您的'nameArray'和'ageArray',並向它們添加了新的對象? – t4nhpt