gpt4 book ai didi

ios - 如何更新 TableView 中的数据(Swift)

转载 作者:IT王子 更新时间:2023-10-29 05:25:47 24 4
gpt4 key购买 nike

我有两个 Swift 文件:NotificationsViewController 和 ViewController。当点击按钮时,firstArray 在 ViewContoller 中更新。我能够打印更新的数据。但是,当我切换回 NotificationsViewController 时,当我拉动刷新时,tableview 没有更新。

通知 View Controller :

import Foundation
import UIKit

var firstArray : [String] = ["123","1234"]

class NotificationsViewController: UITableViewController {


var refresher: UIRefreshControl!

var data: [[String]] = [firstArray, ["4","5"]]

func refresh(){

print("refreshed")
self.tableView.reloadData()
self.refresher.endRefreshing()

}

override func viewDidLoad() {


refresher = UIRefreshControl()
refresher.attributedTitle = NSAttributedString(string: "pull to refresh")

refresher.addTarget(self, action: #selector(NotificationsViewController.refresh), forControlEvents: UIControlEvents.ValueChanged)
self.tableView.addSubview(refresher)
refresh()


super.viewDidLoad()
self.tableView.editing = true

}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return data.count

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



return data[section].count

}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: .Subtitle, reuseIdentifier: "tableCell")

cell.textLabel?.text = data[indexPath.section][indexPath.row]

return cell
}

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {

data[indexPath.section].removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)



}
}

}

View Controller :

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()


}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

@IBAction func button(sender: AnyObject) {
firstArray.append("522")
print(firstArray)

}


}

我试过了 this但它也不起作用。

更新:

如何更新基于另一个数组的 cell.detailTextLabel?.text 的值?

提前谢谢你

最佳答案

一期:

更新第一个数组后。您也需要更新数据。它不会自动更新。所以你的代码看起来像

func refresh(){
data = [firstArray, ["4","5"]]
print("refreshed")
self.tableView.reloadData()
self.refresher.endRefreshing()
}

反馈:

与其在类之外使用变量,不如使用单例类。它看起来像这样:

class Singleton: NSObject {
static let sharedInstance = Singleton()
var firstArray = []
}

您可以像这样更新/检索数组

Singleton.sharedInstance.firstArray

关于ios - 如何更新 TableView 中的数据(Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37146801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com