我有一个场景:
ViewController1,ViewController
显示“社区”的 UITableView,并有一个按钮可以加入其他社区,加载另一个 View 。
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 传递到 ViewController,该标志最初设置为 nil(可选类型),甚至 bool 变量也可以做到这一点。这可以通过 prepareForSegue 方法和协议(protocol)委托(delegate)来实现。
UIViewController 生命周期中的方法 viewWillAppear() 每次在 UIViewController 被插入视野时执行,因为在导航堆栈中弹出另一个 UIViewController 在它的顶部。所以基本上你只需要检查 viewWillAppear() 中的标志是否用户已成功注册。
override func viewWillAppear()
{
super.viewWillAppear()
if flag == true
{
communitiesTableView.reloadData()
}
}
用户有可能在注册一次后再次注册。因此,在 UIViewController 的生命周期中的 viewWillDisappear() 方法中禁用此标志,原因是,如果用户实际上没有注册并弹出 UIViewController,则会导致重新加载表格。
如果要重新加载的数据来自某个 API,则需要在 UIViewController 的生命周期中调用 willViewAppear() 方法中的 Web 服务,并在收到请求后重新加载表格响应。
如果多次重新加载数据没有问题,只需在 viewWillAppear() 中重新加载数据即可。 但这不是一个好的做法,因为它最大限度地减少了应用程序的优化,因为每次都在用户不进行注册的情况下重新加载数据。
关于ios - 如何从另一个 View Controller 更新 UITableView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40205840/