点击后退按钮时如何在UITableView中保留更新的数据

时间:2018-09-25 02:41:13

标签: ios swift uitableview back-button

我正在创建一个事件应用程序,其中从API提取的参与者列表在UITableView中列出。当用户轻按checkInOutbutton时,事件check inregister或事件后check out。用户从事件签入签出的每一次之后,用户都应pull to refresh更新表中的数据。我使用下面的代码来更新数据。

var refresher: UIRefreshControl!

 override func viewDidLoad() {
    super.viewDidLoad()

  refresher = UIRefreshControl()
    refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")
    refresher.addTarget(self, action: #selector(ParticipantsViewController.refresh), for: UIControlEvents.valueChanged)
    ParticipantTableView.addSubview(refresher)


}

//MARK: FUNCTIONS

@objc func refresh() {

    refresher.endRefreshing()
    getParticipants()
    ParticipantTableView.reloadData()
     _ = SCLAlertView(appearance: Appearance).showSuccess("Success", subTitle: "Participants Updated!")
}

使用pull to refresh后,我成功更新了表。问题是,当我轻按back button进入我的dashboard并轻按该按钮返回我的UItableview的VC时,该UItableview是participantViewController, the data is not updated. It goes back to its original data. How can I retain the updated data even if I tapped the back button and goes back to the个参与者or注册参与者的VC ?希望你能帮助我。

原始数据,灰色bgcolor和未注册标签(签入和签出按钮位于折叠单元格内

original data, gray bgcolor and NOT REGISTERED label(checkin and checkout button is inside the folding cell)

数据,一旦用户点击“签到”按钮,背景颜色变为绿色并且标签已注册

data once the user tapped checkin button, the background colour turned to green and label is REGISTERED

点击后退按钮时的仪表板

Dashboard when back button is tapped

点击后退按钮

 @IBAction func backbutton(_ sender: UIButton) {
     self.dismiss(animated: true, completion: nil)
}

ParticipantViewController

import UIKit
import FoldingCell
import SCLAlertView
import AASquaresLoading

class ParticipantsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var ParticipantTableView: UITableView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var countLabel: UILabel!
@IBOutlet weak var notifImageView: UIImageView!

var refresher: UIRefreshControl!

var validPincode: String!
var titleString: String!

var participants: [Attendee]!
var filteredParticipants = [Attendee]()


let kCloseCellHeight: CGFloat = 122
let kOpenCellHeight: CGFloat = 475

var cellHeights = [CGFloat]()

let searchController = UISearchController(searchResultsController: nil)


override func viewDidLoad() {
    super.viewDidLoad()

    createCellHeightsArray()
    configureSearchBar()
    configureAALoading()
    countNotif()

    titleLabel.text = self.titleString

    refresher = UIRefreshControl()
    refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")
    refresher.addTarget(self, action: #selector(ParticipantsViewController.refresh), for: UIControlEvents.valueChanged)
    ParticipantTableView.addSubview(refresher)


}

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


override func viewDidAppear(_ animated: Bool) {
    self.ParticipantTableView.reloadData()
}



@IBAction func backbutton(_ sender: UIButton) {
     self.dismiss(animated: true, completion: nil)
}



//MARK: FUNCTIONS

@objc func refresh() {

    refresher.endRefreshing()
    getParticipants()
    ParticipantTableView.reloadData()
     _ = SCLAlertView(appearance: Appearance).showSuccess("Success", subTitle: "Participants Updated!")


}


func configureAALoading() {
    self.view.squareLoading.color = UIColor(red: 80/255.0, green: 187/255.0, blue: 113/255.0, alpha: 1.0)
    self.view.squareLoading.backgroundColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.7)
}

func getParticipants() {

    var participantType: ParticipantType!

    if self.titleString == "PARTICIPANTS" {
        participantType = .all
    }else {
        participantType = .active
    }

    self.view.squareLoading.start(0.0)

    let api = APIService()

    api.getParticipants(enteredPincode: validPincode, participantType: participantType, successBlock: { (attendees) in

         self.participants = attendees
        self.view.squareLoading.stop(0.0)

        if self.searchController.isActive && self.searchController.searchBar.text != "" {
            self.filterContentForSearchText(searchText: self.searchController.searchBar.text!)
        }else {
            self.ParticipantTableView.reloadData()
        }



    }) { (error) in
        // Hide loading view
        self.view.squareLoading.stop(0.0)
        _ = SCLAlertView(appearance: Appearance).showError("Network Error", subTitle: "\(error)")

    }


}



func countNotif(){

    if participants.count == 0 {
        countLabel.isHidden = true
        notifImageView.isHidden = true

    }else {
        countLabel.text = "\(participants.count)"
        notifImageView.image = #imageLiteral(resourceName: "participant_notif")
    }
}


  func createCellHeightsArray() {

    cellHeights.removeAll()

    if searchController.isActive && searchController.searchBar.text != "" {
        for _ in 0...filteredParticipants.count {
            cellHeights.append(kCloseCellHeight)
        }
    }else {
        for _ in 0...participants.count {
            cellHeights.append(kCloseCellHeight)
        }
    }
}


    func filterContentForSearchText(searchText: String, scope: String = "All") {
        filteredParticipants = participants.filter { participants in
            return participants.displayName.lowercased().contains(searchText.lowercased()) || (participants.department.lowercased().contains(searchText.lowercased()))
            //                || (participants.employeeNumber?.contains(searchText))! ||
        }

        createCellHeightsArray()
        ParticipantTableView.reloadData()

    }

func configureSearchBar() {

    searchController.searchResultsUpdater = self
    searchController.dimsBackgroundDuringPresentation = false
    definesPresentationContext = true

    searchController.searchBar.textColor = UIColor.white
    searchController.searchBar.placeholder = "Search by name, department, and employee number"
    searchController.searchBar.searchBarStyle = .minimal
    searchController.searchBar.barTintColor = UIColor(red: 26/255.0, green: 99/255, blue: 42/255, alpha: 1.0)
    searchController.searchBar.tintColor = UIColor.white
    searchController.searchBar.backgroundColor = UIColor(red: 26/255.0, green: 99/255, blue: 42/255, alpha: 1.0)

    searchController.searchBar.isTranslucent = false

    self.ParticipantTableView.tableHeaderView = searchController.searchBar
}



// MARK: TABLE VIEW DATA SOURCE



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

    if searchController.isActive && searchController.searchBar.text != "" {
        return filteredParticipants.count
    }
    //print(participants.count)
    return (participants.count)
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "FoldingCell", for: indexPath)
           return cell
}

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {

    guard case let cell as ParticipantCell = cell else {
        return
    }

    cell.backgroundColor = UIColor.clear

    if searchController.isActive && searchController.searchBar.text != "" {
        cell.participant = filteredParticipants[indexPath.row]
    }else {
        cell.participant = participants[indexPath.row]
    }

    if cellHeights[(indexPath as NSIndexPath).row] == kCloseCellHeight {
        cell.unfold(false, animated: false, completion: nil)
    } else {
        cell.unfold(true, animated: false, completion: nil)
    }
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return cellHeights[(indexPath as NSIndexPath).row]
}

// MARK: TABLE VIEW DELEGATE

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let cell = tableView.cellForRow(at: indexPath) as! FoldingCell

    if cell.isAnimating() {
        return
    }

    var duration = 0.0

    if cellHeights[(indexPath as NSIndexPath).row] == kCloseCellHeight { // open cell
        cellHeights[(indexPath as NSIndexPath).row] = kOpenCellHeight
        cell.unfold(true, animated: true, completion: nil)
        duration = 0.3
    } else {// close cell
        cellHeights[(indexPath as NSIndexPath).row] = kCloseCellHeight
        cell.unfold(false, animated: true, completion: nil)
        duration = 0.5
    }

    UIView.animate(withDuration: duration, delay: 0, options: .curveEaseOut, animations: { () -> Void in
        tableView.beginUpdates()
        tableView.endUpdates()
    }, completion: nil)

    }

}

extension ParticipantsViewController: UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
    filterContentForSearchText(searchText: searchController.searchBar.text!)
    }
}

extension UISearchBar {

var textColor: UIColor? {
    get {
        if let textField = self.value(forKey: "searchField") as? UITextField {
            return textField.textColor
        }else {
            return nil
        }
    }

    set (newValue) {
        if let textField = self.value(forKey: "searchField") as? UITextField {
            textField.textColor = newValue
            textField.font = UIFont(name: "HelveticaNeue", size: 20.0)
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您对问题的解释让我有些困惑,但我想我理解您的意思。我的解释:您提供一个tableView的视图控制器,并使用一些新数据刷新该表视图。然后,当您关闭视图控制器并返回到它时,新数据消失了,您只看到了旧数据。

如果这是您的问题,那么解决方案非常简单。当您返回视图控制器时,您可能只是在创建一个全新的viewController并将其呈现出来……这将不会具有从网络中获取的新数据。

在这种情况下,您必须将原始的viewController实例存储在变量中并显示THAT,而不是创建一个全新的实例。

编辑:

在仪表板代码中的某处,您可能有此行

self.present(ParticipantsViewController(), animated: false)

...或其他形式。代替这个,做一些...

class DashboardViewController: UIViewController{

 var participantsViewController = ParticipantsViewController()

    func responseToSomeUserAction(){
        self.present(self.participantsViewController, animated: true)
    }

}

在上面的代码中,每次用户想要显示表视图时,都会显示相同的viewController实例,因此所有数据仍将存在。