我正在做一个基本的Contactlist应用程序。但是我在DetailViewController中提供的细节不会保存并显示在我的MasterViewController中。

时间:2015-05-15 06:40:35

标签: ios xcode swift

我正在创建一个基本上是联系人列表的简单应用程序。我的MasterViewController有我的所有联系人,DetailViewController有联系人的详细信息,例如:firstname,middlename,lastname等。当我在DetailViewController中输入数据时,它应该保存并点击后退按钮自动保存这些数据。除此之外的一切都很好。我输入数据并点击后退按钮,数据无法保存。如果我能得到任何帮助,我将不胜感激。我知道这是一个简单的错误,但我无法弄清楚它是什么。

DetailViewController

import UIKit

protocol DetailViewControllerDelegate{
func detailViewController(dvc: DetailViewController, didUpdate contact:Person)
}

class DetailViewController: UIViewController {

var delegate: DetailViewControllerDelegate?
var contact: ContactListEntry!


@IBOutlet weak var txtphonenumber: UITextField!

@IBOutlet weak var txtlastname: UITextField!
@IBOutlet weak var address: UITextField!
@IBOutlet weak var yearOfBirth: UITextField!


@IBOutlet weak var middleName: UITextField!
@IBOutlet weak var firstName: UITextField!
@IBAction func okPressed(sender: AnyObject) {

    if let lastname = txtlastname.text
    {
        if let phonenumber = txtphonenumber.text
        {
            if let firstName = firstName.text
            {

                if let middleName = middleName.text
                {

                    if let yearOfBirth = yearOfBirth.text
                    {
                        contact.lastName = lastname
                        contact.phoneNumber = phonenumber
                        contact.firstName = firstName
                        contact.middleName = middleName
                        contact.yearOfBirth = yearOfBirth.toInt()

                        delegate?.detailViewController(self,didUpdate: contact)
                    }
            }
        }

    }
}
}
override func viewDidAppear(animated: Bool) {
    firstName.text = "\(contact.firstName)"
    txtlastname.text = "\(contact.lastName)"
    txtphonenumber.text = "\(contact.phoneNumber)"

}

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

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


}

MasterViewController

import UIKit

class contactTableViewController: UITableViewController,         
DetailViewControllerDelegate{

var contacts: [ContactListEntry] = []
var currentContact: ContactListEntry!

var detailObject: DetailViewController!

override func viewDidLoad() {
    super.viewDidLoad()

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    self.navigationItem.leftBarButtonItem = self.editButtonItem()
}

@IBAction func addContact(sender: AnyObject) {


    currentContact = ContactListEntry(firstName: "", lastName: "", phoneNumber: "123")
    contacts.append(currentContact)
    performSegueWithIdentifier("showDetail", sender: self)
}


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

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return contacts.count
}


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

    let contact = contacts[indexPath.row]

        cell.textLabel?.text = "\(contact.firstName) ,\(contact.lastName) ,\(contact.phoneNumber)"



    return cell
}


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


// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
        contacts.removeAtIndex(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    } else if editingStyle == .Insert {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }    
}


/*
// 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
}
*/


// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if let cell = sender as? UITableViewCell
    {
        let indexPath = tableView.indexPathForCell(cell)!
        currentContact = contacts[indexPath.row]

    }
    if let dvc = segue.destinationViewController as? DetailViewController
    {
        dvc.contact = currentContact
        dvc.delegate = self
    }
}

func detailViewController(dvc: DetailViewController, didUpdate contact: Person)
{
    dvc.dismissViewControllerAnimated(true, completion: nil)
    navigationController?.popToViewController(self, animated: true)
    tableView.reloadData()
}


}

Swift文件

import Foundation
class Person{

var firstName: String
var middleName: String?
var lastName: String
var yearOfBirth: Int?
let currentYear = NSCalendar.currentCalendar().component(NSCalendarUnit.CalendarUnitYear, fromDate: NSDate())
//delegated initialiser
init(firstName: String, lastName: String, yearOfBirth: Int? = nil, middleName: String? = nil)
{
    self.firstName = firstName
    self.lastName = lastName
    self.yearOfBirth = yearOfBirth
    self.middleName = middleName
}

//convenience initialiser
convenience init(firstName: String, lastName: String, age: Int, middleName: String? = nil)
{
    self.init(firstName: firstName, lastName: lastName, age: age, middleName: middleName)
}

//Age as computed property
//This calculates the age from the current year and year of birth
var age: Int!{
    get{
        self.age = currentYear - yearOfBirth!
        return self.age
    }
    set{

        self.yearOfBirth = currentYear - age
    }
}

//Fullname function which returns the fullname of the person when first name and last name is entered
func fullName() -> String
{

    if middleName != nil{
        return firstName + " " + middleName! + " " + lastName

    } else {
        return firstName + " " + lastName
    }
}
  }

// A subclass of person class that accepts address and phone number too

class ContactListEntry: Person{
var address : String?
var phoneNumber : String?
init(firstName: String, lastName: String, yearOfBirth: Int? = nil,     middleName: String? = nil, address: String? = nil, phoneNumber: String? = ""){
    self.address = address
    self.phoneNumber = phoneNumber
    super.init(firstName: firstName, lastName: lastName, yearOfBirth:     yearOfBirth?, middleName: middleName?)
}
}

// Class to accept the contact list entries
class ContactList{

var entries: [ContactListEntry]=[]

 }

1 个答案:

答案 0 :(得分:0)

首先,从Swift 1.2开始,你可以绑定多个选项,不需要嵌套的if

if let lastname = txtlastname.text, 
    phonenumber = txtphonenumber.text, 
    firstName = firstName.text, 
    middleName = middleName.text, 
    yearOfBirth = yearOfBirth.text {
    // ...
}

更新:看起来您点按系统提供的'返回'按钮,在您执行segue到详细视图后自动出现在导航栏中。如果是这种情况,只需将代码从okPressed()移至viewWillDisappear()方法即可。然后,在detailViewController(dvc: DetailViewController, didUpdate contact:Person)方法中,您只需拥有tableView.reloadData(),即可摆脱其余部分。希望这有效!