我有两个Swift文件:NotificationsViewController和ViewController。轻按按钮时,将在ViewContoller中更新firstArray。我能够打印更新的数据。但是,当我切换回NotificationsViewController时,刷新时不会更新tableview。
NotificationsViewController:
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)
}
}
}
ViewController:
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)
}
}
我试过了,但是也没有用。
更新 :
如何更新基于另一个数组的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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句