2015-06-17 2 views
0

У меня проблема с моим быстрым кодом. У меня есть UITableViewCotroller с ячейкой прототипа, в этой ячейке есть три метки. Я создал файл TimerCell.swift с @IBOutlet для меток:Как передать данные в AddController в UITableViewController

import UIKit 

class TimerCell: UITableViewCell { 

@IBOutlet var circostanza: UILabel! 
@IBOutlet var luogo: UILabel! 
@IBOutlet var tempo: UILabel! 


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

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

    // Configure the view for the selected state 
} 

} 

и файл TimerModel.swift с этим кодом:

import UIKit 

class TimerModel: NSObject, NSCoding { 


var circostanza :String! 
var luogo : String! 
var tempo : String! 


init(circostanzaIn:String, luogoIn:String, tempoIn:String) { 
    circostanza = circostanzaIn 
    luogo = luogoIn 
    tempo = tempoIn 
} 

internal required init(coder aDecoder: NSCoder) { 
    self.circostanza = aDecoder.decodeObjectForKey("circostanza") as! String 
    self.luogo = aDecoder.decodeObjectForKey("luogo") as! String 
    self.tempo = aDecoder.decodeObjectForKey("tempo") as! String 
    } 

func encodeWithCoder(encoder: NSCoder) { 
    encoder.encodeObject(self.circostanza, forKey: "circostanza") 
    encoder.encodeObject(self.luogo, forKey: "luogo") 
    encoder.encodeObject(self.tempo, forKey: "tempo") 
} 


} 

Тогда у меня есть кнопка + в UITableViewCotroller, чтобы открыть AddController с тремя текстовыми полями, чтобы добавить некоторые данные. Я хочу сохранить эти данные в ярлыках ячейки. Код в AddController является:

import UIKit 

class AddTimerController: UIViewController, UITextFieldDelegate { 

@IBOutlet var fieldCircostanza: UITextField! 
@IBOutlet var fieldLuogo: UITextField! 
@IBOutlet var fieldTempo: UITextField! 


override func viewDidLoad() { 
    super.viewDidLoad() 


    fieldCircostanza.delegate = self 
    fieldLuogo.delegate = self 


    // 
    var keyboardToolbar = UIToolbar(frame: CGRectMake(0, 0, self.view.bounds.size.width, 44)) 
    keyboardToolbar.barStyle = UIBarStyle.BlackTranslucent 
    keyboardToolbar.backgroundColor = UIColor.redColor() 
    keyboardToolbar.tintColor = UIColor.whiteColor() 
    var flex = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) 
    var save = UIBarButtonItem(title: "Fatto", style: UIBarButtonItemStyle.Done, target: fieldTempo, action: "resignFirstResponder") 
    keyboardToolbar.setItems([flex, save], animated: false) 
    fieldTempo.inputAccessoryView = keyboardToolbar 
} 


func textFieldShouldReturn(textField: UITextField) -> Bool { 
    textField.resignFirstResponder() // chiudere la tastiera nei campi di testo 
    return true 
} 


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

@IBAction func annulla(sender: UIButton) { 
    dismissViewControllerAnimated(true, completion: nil) // chiude una modal 
} 

@IBAction func salva(sender: UIButton) { 
    if fieldCircostanza.text.isEmpty && 
     fieldLuogo.text.isEmpty && 
     fieldTempo.text.isEmpty{ 
      //alertView 
      return 
    } 

    var timer = TimerModel(circostanzaIn: fieldCircostanza.text, 
     luogoIn: fieldLuogo.text, 
     tempoIn: fieldTempo.text) 


    DataManager.sharedInstance.salvaArray() 
    DataManager.sharedInstance.detail.myCollection.reloadData() 

    dismissViewControllerAnimated(true, completion: nil) 
} 

} 

Наконец UITableViewCotroller файл:

import UIKit 

class TimerViewController: UITableViewController { 

override func viewDidLoad() { 
    super.viewDidLoad() 


} 

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

// MARK: - Table view data source 

override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return 1 
} 

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

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

    //cell.circostanza.text = timer.circostanza 
    //cell.luogo.text = timer.luogo 
    //cell.tempo.text = timer.tempo 


    return cell 
} 

override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { 
    // Return false if you do not want the specified item to be editable. 
    return true 
} 

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { 
    if editingStyle == .Delete { 

     DataManager.sharedInstance.storage.removeAtIndex(indexPath.row) 
     DataManager.sharedInstance.salvaArray() 

     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. 
    } 
} 

// MARK: - Navigazione 

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
    if segue.identifier == "modifica" { 
     //let controller = (segue.destinationViewController as UINavigationController).topViewController as AddController 

    } 
} 


} 

Можете ли вы мне помочь с кодом для сохранения данных?

+0

поэтому, какая ошибка вы получаете ?? –

+0

Привет, в AddController, когда я нажимаю кнопку сохранения, данные, которые я добавил в текстовые поля, не сохраняются в ярлыках ячейки в UITableViewController. – Elis

+0

ОК, так что вы не получаете никаких сбоев или ошибок, просто значения не обновляются в необходимых ярлыках? –

ответ

0

Для доступа таймера в tableViewController, сделайте следующее:

import UIKit 

class AddTimerController: UIViewController, UITextFieldDelegate { 

@IBOutlet var fieldCircostanza: UITextField! 
@IBOutlet var fieldLuogo: UITextField! 
@IBOutlet var fieldTempo: UITextField! 

var timer: TimerModel! // Made timer a class member 

override func viewDidLoad() { 
    ...... 
} 

// your code .... 

@IBAction func salva(sender: UIButton) { 
    if fieldCircostanza.text.isEmpty && 
     fieldLuogo.text.isEmpty && 
     fieldTempo.text.isEmpty{ 
      //alertView 
      return 
    } 

    timer = TimerModel(circostanzaIn: fieldCircostanza.text, // intialize timer 
     luogoIn: fieldLuogo.text, 
     tempoIn: fieldTempo.text) 


    DataManager.sharedInstance.salvaArray() 
    DataManager.sharedInstance.detail.myCollection.reloadData() 

    dismissViewControllerAnimated(true, completion: nil) 
} 

} 

и после этого в tableViewController, доступ к нему, как это:

class TimerViewController: UITableViewController { 

    var timer: TimerModel! // Change to this 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     var controller : AddTimerController = AddTimerController() 
     timer = controller.timer 
    } 

    // your code ....... 

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

     cell.circostanza.text = timer.circostanza 
     cell.luogo.text = timer.luogo 
     cell.tempo.text = timer.tempo 

     return cell 
    } 
    } 
+0

Спасибо за вашу доступность, но теперь у меня есть ошибка: ** Не могу вызвать инициализатор для типа «TimerModel» без аргументов ** в файле TimerViewController в строке: 'var timer: TimerModel = TimerModel()' – Elis

+0

Привет, для этого просто предоставить функцию init в вашем timermodel –

0

для вашего запроса в комментарии, это будет правильно, что:

В вашем TimerModel:

import UIKit 

    class TimerModel: NSObject, NSCoding { 


    var circostanza :String! 
    var luogo : String! 
    var tempo : String! 


    override init() { // add this method 
     super.init() 
    } 

    init(circostanzaIn:String, luogoIn:String, tempoIn:String) { 
     circostanza = circostanzaIn 
     luogo = luogoIn 
     tempo = tempoIn 
    } 

    internal required init(coder aDecoder: NSCoder) { 
     self.circostanza = aDecoder.decodeObjectForKey("circostanza") as! String 
     self.luogo = aDecoder.decodeObjectForKey("luogo") as! String 
     self.tempo = aDecoder.decodeObjectForKey("tempo") as! String 
     } 

    func encodeWithCoder(encoder: NSCoder) { 
     encoder.encodeObject(self.circostanza, forKey: "circostanza") 
     encoder.encodeObject(self.luogo, forKey: "luogo") 
     encoder.encodeObject(self.tempo, forKey: "tempo") 
    } 


    } 
+0

У меня есть сбой, указанная строка: 'timer = controller.timer' в файле TimerViewController – Elis

+0

вы можете дать полную ошибку? –

+0

Привет, вы можете скачать изображение по этой ссылке: http: // d.pr/i/1kpzl – Elis