gpt4 book ai didi

swift - 添加对象后更新表格 View

转载 作者:行者123 更新时间:2023-11-30 10:01:45 26 4
gpt4 key购买 nike

我正在使用 coredata 保存字符串,并且我保存的所有字符串将在表格 View 中显示为标签文本。字符串来自警报 View 中的文本字段。它正确保存了字符串,但我必须关闭并再次运行项目,然后新字符串才会显示在表格 View 中。

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet var tableView: UITableView!

var buyingList : [BuyList] = []

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

gettingData()


self.tableView.dataSource = self
self.tableView.delegate = self

}


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.buyingList.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// let Cell = tableView.dequeueReusableCellWithIdentifier("identifier") as UITableViewCell!
let Cell = UITableViewCell()



let tableViewData = self.buyingList.reverse()[indexPath.row]
Cell.textLabel?.text = tableViewData.buyList

return Cell
}

func refresh(){
dispatch_async(dispatch_get_main_queue()) { () -> Void in
dump(self.buyingList)
self.tableView.reloadData()
}
}

@IBAction func addButton(sender: UIBarButtonItem) {
nameOfPicture()
}

func nameOfPicture() {
let alert = UIAlertController(title: "Tilføj", message: "", preferredStyle: UIAlertControllerStyle.Alert)

let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
alert.addAction(cancel)

alert.addTextFieldWithConfigurationHandler { (textField) -> Void in

}

alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in

let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

let savingData = NSEntityDescription.insertNewObjectForEntityForName("BuyList", inManagedObjectContext: context) as! BuyList

let textf = alert.textFields![0] as UITextField

savingData.buyList = textf.text

do {
try context.save()

} catch _ {

}

}))

self.presentViewController(alert, animated: true, completion: nil)
}

func gettingData() {
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

let request = NSFetchRequest(entityName: "BuyList")

var results : [AnyObject]?

do {
results = try context.executeFetchRequest(request)
} catch _ {
results = nil
}

if results != nil {
self.buyingList = results! as! [BuyList]
}
}
}

最佳答案

获取数据后,表格 View 不会重新加载。您的获取数据函数应如下所示:

if results != nil {
self.buyingList = results! as! [BuyList]
self.tableView.reloadData()
}

如果此调用后没有在您的表中显示数据,则意味着您的结果因此您的购买列表为空

关于swift - 添加对象后更新表格 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38132369/

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