swift - Userdefaults Tableview 地标 Swift 3

标签 swift swift3 tableview nsuserdefaults

我正在使用uitableview。当我选择一个单元格时,我试图保存地标。从下面的代码中,我添加了一个表格 View ,当我选择一个单元格时,将显示地标。但我在保存它时遇到了麻烦,因为当我转到另一个 View Controller 并返回时它不会显示。我研究过并发现我需要使用 UserDefaults 但我不知道如何使用它。有人能指出我如何才能实现这一目标吗?谢谢

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

    let contactsCell = app.helper.contacts[indexPath.row]
    cell!.textLabel?.text = contactsCell

    return cell!
}


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

    let contactToCall = app.helper.contacts[indexPath.row]
    app.helper.contactSelected = contactToCall

    if let cell = tableView.cellForRow(at: indexPath) {
        if cell.isSelected {
            cell.accessoryType = .checkmark


        }
    }

}

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

    if let cell = tableView.cellForRow(at: indexPath) {
        cell.accessoryType = .none
    }
}

最佳答案

除非您想在应用程序关闭并重新启动后保持状态,否则您不需要 UserDefaults,并且一旦开始存储用户默认值,您可能想要存储更多 - 因此创建默认值是有意义的数据类来存储选定的索引和您可能需要的任何其他“内容”。

在此示例中,我将在 viewDidLoad 上加载默认值,并在每次选择/取消选择时存储默认值。如果您存储了其他值,则应该进行额外的存储调用。

创建一个类来存储数据

class MyDefaultsData : NSObject, NSCoding
{
    var selectedIndexPath : IndexPath?
    var otherStuff : String?

    override init()
    {
        // you can set up default values here if you need them
        selectedIndexPath = nil
        otherStuff = nil
    }

    // archiving code
    func encode(with aCoder: NSCoder)
    {
        // you can't store IndexPath directly, so split it into row and section
        if selectedIndexPath == nil
        {
            // set invalid values which we can identify later
            aCoder.encode(-1, forKey: "indexSection")
            aCoder.encode(-1, forKey: "indexRow")
        }
        else
        {
            aCoder.encode(selectedIndexPath!.section, forKey: "indexSection")
            aCoder.encode(selectedIndexPath!.row, forKey: "indexRow")
        }
        aCoder.encode(otherStuff, forKey: "otherStuff")
    }

    required init(coder aDecoder: NSCoder)
    {
        let indexSection = aDecoder.decodeInteger(forKey: "indexSection")
        let indexRow = aDecoder.decodeInteger(forKey: "indexRow")
        if indexSection != -1 && indexRow != -1  // if no row is selected, these values will both be -1
        {
            selectedIndexPath   = IndexPath(row: indexRow, section: indexSection)
        }
        else
        {
            selectedIndexPath = nil
        }

        self.otherStuff     = aDecoder.decodeObject(forKey: "otherStuff") as? String
    }

}

在 ViewController 中定义默认数据的变量

var defaultData         = MyDefaultsData()

viewDidLoad 中加载数据

override func viewDidLoad()
{
    loadDefaults()
}

func loadDefaults()
{
    var dataDefaults : MyDefaultsData?
    if let data = UserDefaults.standard.object(forKey: "NSDefaultsTest") as? Data
    {
        dataDefaults =  NSKeyedUnarchiver.unarchiveObject(with: data) as? MyDefaultsData

        self.defaultData.otherStuff = dataDefaults?.otherStuff ?? "No value found"

        self.defaultData.selectedIndexPath = dataDefaults?.selectedIndexPath
    }
}

然后您在cellForRowAt中使用默认数据

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

    let contactsCell = app.helper.contacts[indexPath.row]
    cell!.textLabel?.text = contactsCell

    // set or clear the checkmark
    if selectedIndexPath == indexPath
    {
        cell.accessoryType = .checkmark
    }
    else
    {
        cell.accessoryType = .none
    }
    return cell!
}

当您更改选定的行时,您需要重新加载先前选定的行(如果有)和当前选定的行,以绘制复选标记

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    let previousIndexPath = defaultData.selectedIndexPath
    if previousIndexPath != indexPath
    {
        defaultData.selectedIndexPath = indexPath
    }
    else
    {
        defaultData.selectedIndexPath = nil
    }
    storeDefaults()


    if previousIndexPath != nil
    {
        tableView.reloadRows(at: [previousIndexPath!], with: .automatic)
    }
    if defaultData.selectedIndexPath != nil
    {
        tableView.reloadRows(at: [defaultData.selectedIndexPath!], with: .automatic)
    }
}

关于swift - Userdefaults Tableview 地标 Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41842418/

相关文章:

导航栏中的 iOS 11 UISearchBar

ios - 在 Swift 中,如何将 "°"转换为 "°"(即度数符号)?使用内置的 Cocoa 实用程序(使用 NSAttributedString)

Swift - 检测项目是否被插入到 NSMutableSet

ios - 当手机上没有安装 Facebook 应用程序时,如何在 iOS 应用程序中将照片分享到 Facebook?

ios - 执行 segue 时,主线程上的 UI 未更新

swift - UITableViewCell 不显示数据

swift - 以编程方式更改热敏蓝牙打印机上的字体大小

swift3 - 使用 swift 3 登录 Facebook

swift - 单元格中的 2 个项目具有相同的 tapGestureRecognizer (swift)

ios - 如何从 TableView 单元格中的按钮进入新的 View Controller