Swift 4,使用Array和TableViewCell存储和显示数据

时间:2018-05-09 21:42:22

标签: ios uitableview core-data swift4 userdefaults

我正在制作一个允许用户按用户名和密码排序的应用程序。目前,当用户退出应用程序时,我遇到问题,数据或TableViewCell未存储或显示。我正在使用数组。

我假设因为之后没有存储数据。 CoreData或UserDefaults是一个简单的解决方案吗?我想避开Firebase。

有人可以解释或展示如何在代码中实现CoreData / UserDefaults吗? 我搜索了很多,但我发现很难理解如何在我的代码中应用它,特别是对于数组和TableViewCell。非常感谢帮助。

图片如下。

这是我的代码:

MainViewController:

class MainViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView:UITableView?


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 tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return informasjoner.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "InformasjonTableViewCell") as! InformasjonTableViewCell

    let informasjon:Informasjon = informasjoner[indexPath.row];

    if(informasjon.image != nil){
        cell.imageViewInfo?.image = informasjon.image
    } else {
        cell.imageViewInfo?.image = UIImage(named: informasjon.imageName!)
    }

    cell.epostLabel?.text = informasjon.labelEpost
    cell.passordLabel?.text = informasjon.labelPassord
    cell.applikasjonLabel?.text = informasjon.labelApplikasjon

    return cell
}

// EDIT / UPDATE CELL

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let informasjon = informasjoner[indexPath.row]

    let deleteAction = UITableViewRowAction(style: .default, title: "Delete"){
        (action, indexPath) in
        self.deleteAction(informasjon: informasjon, indexPath: indexPath)
    }
        //call delete action
    deleteAction.backgroundColor = .red;
    return [deleteAction]
    }
private func deleteAction(informasjon: Informasjon, indexPath: IndexPath){
let alert = UIAlertController(title: "Delete",
                              message: "Are u sure?",
                              preferredStyle: .alert)

    let deleteAction = UIAlertAction(title: "Yes",
                                     style: .default){ (action) in
        informasjoner.remove(at: indexPath.row)
        self.tableView?.deleteRows(at: [indexPath], with: .automatic)

    }
    let cancelAction = UIAlertAction(title: "No",
                                     style: .default,
                                     handler: nil);
    alert.addAction(deleteAction);
    alert.addAction(cancelAction);
    present(alert, animated: true);

}
}

InformasjonTableViewCell:

 import UIKit

 class InformasjonTableViewCell: UITableViewCell {


@IBOutlet weak var imageViewInfo: UIImageView?
@IBOutlet weak var epostLabel: UILabel?
@IBOutlet weak var passordLabel: UILabel?
@IBOutlet weak var applikasjonLabel: UILabel!




override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
    super.setSelected(selected, animated: animated)


}

}

AddInfoVC:

import UIKit

class AddInfoVC: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

@IBOutlet weak var txtEpost:UITextField?
@IBOutlet weak var ImageInfo:UIImageView?
@IBOutlet weak var txtPassord:UITextField?
@IBOutlet weak var txtApplikasjon: UITextField!


var newInfo = Informasjon()

@IBAction func btnSave(sender:UIButton){
print("Press Save!")
    if(newInfo.image == nil || newInfo.labelEpost?.count == 0 || newInfo.labelPassord?.count == 0 || newInfo.labelApplikasjon?.count == 0){
        let alertController = UIAlertController(title: "Alert", message: "Please set", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default){
            (action) in
        }
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil);

    } else{
        informasjoner.append(newInfo);
        navigationController?.popViewController(animated: true)
        let mainViewController = self.navigationController?.topViewController as? MainViewController
        mainViewController?.tableView?.reloadData()
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    //Tap to ImageView
    let tapGestureToImageView = UITapGestureRecognizer(target: self, action: #selector(tapToImageView(sender:)))
    tapGestureToImageView.numberOfTapsRequired = 1
    ImageInfo?.isUserInteractionEnabled = true;
    ImageInfo?.addGestureRecognizer(tapGestureToImageView);

    self.txtEpost?.delegate = self;
    self.txtPassord?.delegate = self;
    self.txtApplikasjon?.delegate = self;


}

模型

Informasjon.swift:

import Foundation
import UIKit

class Informasjon {
var imageName: String?
var image: UIImage?
var labelEpost: String?
var labelPassord: String?
var labelApplikasjon: String?
convenience init(imageName:String, labelEpost:String, labelPassord:String,labelApplikasjon:String ) {
    self.init()
    self.imageName = imageName
    self.labelEpost = labelEpost
    self.labelPassord = labelPassord
    self.labelApplikasjon = labelApplikasjon
}
}

Picture 1 -> How the Application looks from the Storyboard.

Picture 2 -> How the Application looks from Simulator.

1 个答案:

答案 0 :(得分:0)

UserDefaults 通常是最简单的数据库。如果您只有一个数组来存储/检索,那么请坚持下去。如果您有更多信息,请使用更强大的内容,例如 CoreData / Realm

let array = []()
let defaults = UserDefaults.standard
defaults.set(array, forKey: "SavedStringArray")

请随时查看以下答案和教程。

how to save and read array of array in NSUserdefaults in swift? https://medium.com/@nimjea/userdefaults-in-swift-4-d1a278a0ec79

如果仍然难以理解,我建议您查看 UserDefaults Objective-C 版本 - NSUserDefaults 。即使您不熟悉 Objective-C 语法,它也可能更容易理解。

Save string to the NSUserDefaults?

现在问题是在使用 UITableView 时使用这些方法的位置。

每当您想要从商店更改或检索数据时(在我们的案例中为 UserDefaults )。

对于实例,您可以在tableView(:didSelectRowAt :)中更改存储的数组调用tableView(:cellForRowAt :)方法,或者可以在tableView中检索数据(_:cellForRowAt :)

使用 Realm 查看官方网站 https://realm.io/docs/swift/latest