[英]How can I transfer data from a UITableView to another view controller if the UITableView has cells divided into sections?
[英]How to update UITableView from another View Controller?
我有一個場景:
ViewController1, ViewController
顯示“社區”的UITableView,並有一個按鈕來加入其他社區,這些社區會加載另一個視圖。
ViewController2, JoinCommunity
有一個文本字段和一個連接按鈕。
當用戶輸入正確的社區代碼並單擊“加入”時,這會將用戶注冊到與代碼匹配的社區中。 此時JoinCommunity
被解雇並出現ViewController
。
我的問題是'ViewController'中的UITableView在用戶注銷並重新登錄之前不會更新。
我被告知以下行應該實現它,但它沒有,所以我仍然必須遺漏一些東西:
var communities = [String]() { didSet { communitiesTableView.reloadData()} }
這是ViewController的代碼:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UsernameSentDelegate {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var receiveUsername: UILabel!
@IBOutlet weak var userEmailText: UILabel!
var userEmail: String?
var flag = false
var communities = [String]() { didSet { communitiesTableView.reloadData()
}
}
@IBOutlet weak var communitiesTableView: UITableView!
@IBAction func unwindToHome(_ segue: UIStoryboardSegue) {
}
//recieves email address from delegate from LoginViewController
func userLoggedIn(data: String) {
userEmailText.text = data
}
override func viewDidLoad() {
super.viewDidLoad()
self.communitiesTableView.delegate = self
self.communitiesTableView.dataSource = self
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.communities.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let title = self.communities[indexPath.row]
let cell = UITableViewCell()
cell.textLabel?.text = title
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if segue.identifier == "loginView" {
let loginViewController: LoginViewController = segue.destination as! LoginViewController
loginViewController.delegate = self
}
if segue.identifier == "createCommunitySegue" {
let createCommunityController: CreateNewCommunity = segue.destination as! CreateNewCommunity
createCommunityController.myEmail = userEmailText.text
}
if segue.identifier == "joinCommunitySegue" {
let joinCommunityController: JoinCommunity = segue.destination as! JoinCommunity
joinCommunityController.myEmail = userEmailText.text
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
if flag == true
{
print (flag)
let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/getDetails.php?");
var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";
let postString = "email=\(userEmailText.text)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async
{
if error != nil {
print("error=\(error)")
return
}
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
if let arr = json?["communities"] as? [[String:String]] {
self.communities = arr.flatMap { $0["name"]!
}
}
} catch{
print(error)
}
}
}
task.resume()
}
self.communitiesTableView.delegate = self
self.communitiesTableView.dataSource = self
self.communitiesTableView.reloadData()
}
override func viewDidAppear(_ animated: Bool)
{
communitiesTableView.reloadData()
let isUserLoggedIn = UserDefaults.bool(UserDefaults.standard)(forKey: "isUserLoggedIn");
if(!isUserLoggedIn)
{
self.performSegue(withIdentifier: "loginView", sender: self);
}
}
}
這是JoinCommunity的代碼:
import UIKit
class JoinCommunity: UIViewController {
@IBOutlet weak var communityCodeTextField: UITextField!
@IBAction func goBackTapped(_ sender: AnyObject) {
self.performSegue(withIdentifier: "exitJoin", sender: self)
}
var myEmail: String?
@IBAction func joinCommunityTapped(_ sender: AnyObject) {
let communityCode = communityCodeTextField.text;
if (communityCode!.isEmpty){
displayMyAlertMessage(userMessage: "You must enter Community code");
return;
}else{
let myUrl = URL(string: "http://www.quasisquest.uk/KeepScore/joinCommunity.php?");
var request = URLRequest(url:myUrl!);
request.httpMethod = "POST";
let postString = "code=\(communityCode!)&email=\(myEmail!)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
DispatchQueue.main.async
{
if error != nil {
print("error=\(error)")
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
if let parseJSON = json {
let returnValue = parseJSON["status"] as? String
if( returnValue == "Success")
{
let myAlert = UIAlertController(title: "Alert", message: "Joined new community", preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default){(action) in
self.dismiss(animated: true, completion: nil)
}
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil)
} else {
let errorMessage = parseJSON["message"] as? String
if(errorMessage != nil)
{
self.displayMyAlertMessage(userMessage: errorMessage!);
}
}
}
} catch{
print(error)
}
}
}
task.resume()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func displayMyAlertMessage(userMessage:String)
{
let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"Ok", style: UIAlertActionStyle.default, handler:nil);
myAlert.addAction(okAction);
self.present(myAlert, animated: true, completion: nil);
}
}
將JoinCommunity中的標志傳遞給最初設置為nil(可選類型)的ViewController,甚至布爾變量也可以。 這可以通過prepareForSegue方法以及協議委托來實現。
UIViewController生命周期中的方法viewWillAppear()每次推送UIViewController時都會執行,因為在導航堆棧中彈出了另一個UIViewController。 所以基本上你只需要檢查viewWillAppear()中的標志是否已成功注冊用戶。
override func viewWillAppear()
{
super.viewWillAppear()
if flag == true
{
communitiesTableView.reloadData()
}
}
注冊一次后,用戶可能會再次注冊。 因此,在UIViewController生命周期的viewWillDisappear()方法中禁用此標志的原因是,如果用戶實際上沒有注冊並彈出UIViewController,則會導致重新加載表。
如果要重新加載的數據來自某個API,則需要在UIViewController的生命周期中的willViewAppear()方法中調用Web服務,並在收到響應后重新加載表。
如果多次重新加載數據沒有問題,只需在viewWillAppear()中重新加載數據即可。 但這並不是一個好的做法,因為它可以最大限度地減少應用程序的優化,因為每次重新加載數據而無需用戶進行注冊。
通過代碼,在ViewController上,“communities”是用於填充TableView上的數據的數組。用戶在JoinCommunity Controller上成功加入社區。 你只是解雇了控制器。 ViewController上的'communities'數組從未更新過,因此顯示舊數據。 但是當用戶注銷並登錄時,你說tableview會更新。我猜這是因為在登錄時獲取與用戶關聯的社區
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.