将值保存到TableView中的Textfield的UserDefults:Swift

时间:2015-07-01 14:25:06

标签: swift uitableview nsuserdefaults

我正在尝试从用户将输入到文本字段的tableview中保存值,问题是我不知道如何访问新值并替换数组中的字符串。

因此,应用程序基本上会根据用户的需求显示字段,然后用户可以根据自己的喜好编辑这些值。文本字段更新后,值将再次存储在userdefaults中,以便下次打开tableview时,将显示更新值。

这就是tableviewcontroller目前的样子:

//
//  Asset1TableViewController.swift
//  Net Calc 2
//
//  Created by Joshua Peterson on 30/06/2015.
//  Copyright © 2015 Peterson Productions. All rights reserved.
//

import UIKit

class Asset1TableViewController: UITableViewController {


var dataHolder: [NSString] = [NSString]()
var finalDataHolder: [NSString] = [NSString]()
var acountAmountHolder: [NSString] = [NSString]()
var finalAccountAmountHolder: [NSString] = [NSString]()

let defaults = NSUserDefaults.standardUserDefaults()
let key1 = "keySave1"
let key2 = "keySave2"


override func viewDidLoad() {
    super.viewDidLoad()

         dispatch_async(dispatch_get_main_queue(), { () -> Void in
        if let storedTitleValue : NSArray? = self.defaults.arrayForKey(self.key1) {

            if storedTitleValue == nil {
                self.dataHolder = [NSString]()
            } else {
            let readArray : [NSString] = storedTitleValue as! [NSString]


            for element in readArray {
                self.dataHolder.append(element as String)
                self.finalDataHolder.append(element as String)

            }
        }
    }

            if let storedAmountValue : NSArray? = self.defaults.arrayForKey(self.key2) {

                if storedAmountValue == nil {
                    self.acountAmountHolder = [NSString]()
                } else {
                    let readArray : [NSString] = storedAmountValue as! [NSString]


                    for element in readArray {
                        self.acountAmountHolder.append(element as String)
                        self.finalAccountAmountHolder.append(element as String)

                    }

                }
            }
         })
        }

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}


// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return dataHolder.count
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Account1Cell", forIndexPath: indexPath) as! Account1Cell

    cell.AccountLabel.text = dataHolder[indexPath.row] as String
    cell.AccountAmount.text = acountAmountHolder[indexPath.row] as String

    return cell
}


@IBAction func addButtonTapped(sender: AnyObject) {

    let newAccounTitle = "Account Name"
    let newAccountAmount = "R0.00"

    dataHolder.append(newAccounTitle)
    acountAmountHolder.append(newAccountAmount)

    tableView.reloadData()
    }

@IBAction func saveButtonTapped(sender: AnyObject) {

    // Save
    defaults.setObject(dataHolder as Array, forKey: key1)
    defaults.setObject(acountAmountHolder as Array, forKey: key2)

    defaults.synchronize()

    }

override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == UITableViewCellEditingStyle.Delete {
        dataHolder.removeAtIndex(indexPath.row)
        acountAmountHolder.removeAtIndex(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath],  withRowAnimation: UITableViewRowAnimation.Automatic)
    }
}


/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

}
*/

/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    // Return NO if you do not want the item to be re-orderable.
    return true
}
*/
}

我试图应用我在网站上找到的一些代码,但问题是我实际上无法连接到单元格。

好的,经过一些研究后,我在自定义单元类中添加了一些函数,使它看起来像这样:

import UIKit

protocol TableViewCellDelegate {
  // Indicates that the edit process has begun for the given cell
  func cellDidBeginEditing(editingCell: Account1Cell)
  // Indicates that the edit process has committed for the given cell
  func cellDidEndEditing(editingCell: Account1Cell)
}

class Account1Cell: UITableViewCell,  UITextFieldDelegate {


@IBOutlet weak var AccountLabel: UITextField!
@IBOutlet weak var AccountAmount: UITextField!


var delegate: TableViewCellDelegate?


override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
    AccountLabel.delegate = self

}

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

    // Configure the view for the selected state
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
    // close the keyboard on Enter
    AccountLabel.resignFirstResponder()
    return false
}

func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
    // disable editing of completed to-do items
    return true
}

func textFieldDidEndEditing(textField: UITextField) {

    if AccountLabel != nil {
        let newAccountLabel = AccountLabel.text

        print(newAccountLabel) // Prints out the new edited text!!!!!!!!
    }
    if delegate != nil {
        delegate!.cellDidEndEditing(self)
    }
}

func textFieldDidBeginEditing(textField: UITextField) {
    if delegate != nil {
        delegate!.cellDidBeginEditing(self)
    }
 }



}

现在我需要做的是在索引处替换Array中的那个值(我认为这将是相当复杂的)或创建某种循环来读取所有值并简单地存储所有新的UserDefaults的值。也许还有别的东西?

任何帮助表示赞赏!!

1 个答案:

答案 0 :(得分:1)

您的自定义单元格中应该有这样的协议,并在单元格中的文本字段被修改时调用它:

protocol TableViewCellToTVController{
    func cellCurrentlyEditing(editingCell: Account1Cell) -> Int
}
....
func textFieldShouldReturn(textField: UITextField) -> Bool {
    // close the keyboard on Enter

    let myrow: Int? = self.delegate_special?.cellCurrentlyEditing(self)
    println("cellCurrentlyEditing got called from delegate" , myrow)

    AccountLabel.resignFirstResponder()
    return false
}

在tableviewcontroller中实现此函数以了解选择了哪一行:

func cellCurrentlyEditing(editingCell: Account1Cell) -> Int{
    var rowNum = 0
    let indexP: NSIndexPath = tableView.indexPathForCell(editingCell)!
    rowNum = indexP.row
    return rowNum
}

还使tableviewcontroller成为每个单元格的委托:

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Account1Cell", forIndexPath: indexPath) as! Account1Cell

        cell.AccountLabel.text = dataHolder[indexPath.row] as String
        cell.AccountAmount.text = acountAmountHolder[indexPath.row] as String
        cell.delegate_special = self;
        return cell
    }