文本字段输入表的麻烦

时间:2015-11-17 03:05:09

标签: ios swift uitableview uitextfield

我的主要问题是我没有收到我输入的文字进入我做的标签或表格(有点偏差,但想稍微自定义一下)。我没有收到任何错误,但有人可以看一下这段代码,看看是否有任何重大错误,我可能会忽略它? 编辑:我会继续回去改变类似的小东西,但没有任何效果。这是我的整个代码,以防每个人都更有意义

import UIKit

class ViewController: UIViewController, UITextFieldDelegate, UITableViewDelegate {

var weatherList = [String] ()

@IBOutlet weak var textField: UITextField!

@IBOutlet weak var textLabel: UILabel!

@IBAction func searchButton(sender: AnyObject) {

    weatherList.append(textField.text!)

    textField.text = ""

    NSUserDefaults.standardUserDefaults().setObject(weatherList, forKey: "weatherList")

}

@IBOutlet weak var tableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    if NSUserDefaults.standardUserDefaults().objectForKey("weatherList") != nil {

        weatherList = NSUserDefaults.standardUserDefaults().objectForKey("weatherList") as! [String]

    }

    self.textField.delegate = self

}

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

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

    return weatherList.count

}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")

    cell.textLabel?.text = weatherList[indexPath.row] as String

    return cell

}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

    if editingStyle == UITableViewCellEditingStyle.Delete {

        weatherList.removeAtIndex(indexPath.row)

        NSUserDefaults.standardUserDefaults().setObject(weatherList, forKey: "weatherList")

        tableView.reloadData()

    }

}

override func viewDidAppear(animated: Bool) {
    tableView.reloadData()

}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    self.view.endEditing(true)

}

func textFieldShouldReturn(textField: UITextField) -> Bool {

    textField.resignFirstResponder()

    performAction()

    return true

}

func performAction() {

    weatherList.append(textField.text!)

    textField.text = ""

    NSUserDefaults.standardUserDefaults().setObject(weatherList, forKey: "weatherList")

}

}

1 个答案:

答案 0 :(得分:1)

来自NSUserDefaults class reference

  

NSUserDefaults类提供了便于访问的方法   常见类型,例如浮点数,双精度数,整数,布尔值和URL。一个   默认对象必须是属性列表,即(或   对于集合的实例组合):NSData,NSString,   NSNumber,NSDate,NSArray或NSDictionary。如果你想存储任何   在其他类型的对象中,通常应将其存档以创建   NSData的实例。

这不是快速的数组。请改用NSMutableArray:

var weatherList:NSMutableArray = NSMutableArray()

然后

self.weatherList.addObject(textField.text)