2017-04-19 105 views
-5

我有這樣的代碼在我ViewController1從屏幕傳遞數據到屏幕xcode?

var calendarios = [Calendario]() 
var totalCalendarios1 = 0 

(當屏幕負載totalCalendarios變化和它說,總的正確,我可以看到它在調試) ,我希望它傳遞給我的ViewController2,我有做這個代碼:

let copiaCalendarios = ViewController1() 
let totalCalendarios2 = copiaCalendarios.totalCalendarios1 

我打印了第二個值,它說0,總是,它沒有關係,以前。

我已經使用這個代碼太:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     let destino = segue.destination as? ViewController 
     destino?.calendariosCopia = calendarios 
    } 

,但不起作用。 我在做什麼錯? 搜索的信息,但它是過時的

編輯: 這是我的原代碼: CalendarioViewController是我的第二個VC和CalendarioTableViewController是我的第一個VC和是發送者。

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     let destino = segue.destination as? CalendarioViewController 
     destino?.calendariosCopia = calendarios 
    } 

這是我的代碼有使用,而這一個了:

let copiaCalendarios = CalendarioTableViewController() 
let totalCalendarios = copiaCalendarios.totalCalendarios 
兩個VC

var totalCalendarios = 0

THX IND提前和對不起我的英語不好:$

EDIT2: 這與segue的種類有關嗎? 因爲我用 '出席模態'

EDIT3: CalendarioTableViewController:

// 
// CalendarioTableViewController.swift 
// Vizion5 
// 
// Created by ROB on 16/04/17. 
// Copyright © 2017 ROB. All rights reserved. 
// 

import UIKit 

class CalendarioTableViewController: UITableViewController { 

    var calendarios = [Calendario]() 
    var totalCalendarios = 0 

    func cargarEjemplos() { 

     guard let calendario1 = Calendario(nombre: "2017-A", fin: "17/01/2017", inicio: "05/05/2017") else { 
      fatalError("Error en calendario table view controller") 
     } 

     guard let calendario2 = Calendario(nombre: "2016-A", fin: "17/01/2016", inicio: "05/05/2016") else { 
      fatalError("Error en calendario table view controller") 
     } 

     calendarios += [calendario1, calendario2] 

    } 

    func contarCalendarios() { 
     totalCalendarios = calendarios.count 
    } 

    //AÑADIDO AUTOMATICAMENTE 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     //CARGA LOS EJEMPLOS 
     cargarEjemplos() 
     contarCalendarios() 

     // 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.rightBarButtonItem = self.editButtonItem() 
    } 

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

    // MARK: - Table view data source 

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

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

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     //let identificadorCelda = "tablaCalendario" 
     guard let cell = tableView.dequeueReusableCell(withIdentifier: "tablaCalendario", for: indexPath) as? CalendarioTableViewCell 
      else { 
       fatalError("error 1: calendario table controller") 
     } 

     let calendario = calendarios[indexPath.row] 

     // Configure the cell... 

     cell.nombreCalendario.text = calendario.nombre 
     cell.finCalendario.text = calendario.fin 
     cell.inicioCalendario.text = calendario.inicio 

     return cell 
    } 

    //MARK: ACCIONES 
    @IBAction func regresarATablaCalendario(sender: UIStoryboardSegue) { 
     if let viewControllerOrigen = sender.source as? CalendarioViewController, let calendario = viewControllerOrigen.calendario { 
      //AÑADE EL NUEVO CALENDARIO 
      let newIndexPath = IndexPath(row: calendarios.count, section: 0) 
      calendarios.append(calendario) 
      tableView.insertRows(at: [newIndexPath], with: .automatic) 
     } 
    } 

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     print("Total calendarios es: " + String(totalCalendarios)) 
     let destino = segue.destination as? CalendarioViewController // here you have to use the exact name of your Second View Controller instead of ViewController 
     destino?.totalCalendarios = totalCalendarios 
    } 

} 

我CalendarioViewController

// 
// CalendarioViewController.swift 
// Vizion5 
// 
// Created by ROB on 16/04/17. 
// Copyright © 2017 ROB. All rights reserved. 
// 

import UIKit 

class CalendarioViewController: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate { 

    @IBOutlet weak var nombreCalendario: UITextField! 
    @IBOutlet weak var fechaInicioCalendario: UIDatePicker! 
    @IBOutlet weak var fechaFinCalendario: UIDatePicker! 
    @IBOutlet weak var botonGuardar: UIBarButtonItem! 

    var totalCalendarios = 0 

    //ESTE VALOR SERA PASADO POR 'CALENDARIOVIEWCONTROLLER' EN 'PREPARE(FOR: SENDER:)' O CONTRUIDO PARA AGREGAR UN NUEVO CALENDARIO 
    var calendario: Calendario? 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     nombreCalendario.delegate = self //SE CONTROLA A SI MISMO 

     print("Total segue: " + String(totalCalendarios)) 

     //CHECA SI SE PUEDE HABILITAR EL BOTON DE GAURDADO 
     //DESABILITA EL BOTON DE GUARDADO 
     botonGuardar.isEnabled = false 
     //actualizaEstadoBotonGuardar() 

     // Do any additional setup after loading the view. 
    } 

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

    //MARK: FUNCIONES DE TECLADO Y DETERMINAR FECHA (QUE EL FIN SEA MAYOR QUE INICIO) 

    func textFieldDidBeginEditing(_ textField: UITextField) { 
     botonGuardar.isEnabled = false 
    } 

    func textFieldShouldReturn(_ textField: UITextField) -> Bool { 
     //SE DESHABILITA EL BOTON DE GUARDAR CUANDO SE ESCRIBE 
     botonGuardar.isEnabled = false 
     //ESCONDE EL TECLADO AL PRESIONADO "HECHO" (DONE) 
     textField.resignFirstResponder() 
     return true 
    } 

    func textFieldDidEndEditing(_ textField: UITextField) { 
     actualizaEstadoBotonGuardar() 
     //navigationItem.title = textField.text 
    } 


    // MARK: - NAVEGACION (UNWIND SEGUE) 
    @IBAction func botonCancelar(_ sender: UIBarButtonItem) { 
     dismiss(animated: true, completion: nil) 
    } 

    // In a storyboard-based application, you will often want to do a little preparation before navigation 
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     //super.prepare(for: segue, sender: sender) 
     guard let button = sender as? UIBarButtonItem, button === botonGuardar else { 
      print("Error en prepare sender") 
      return 
     } 

     let setFormatoFecha = DateFormatter() 
     setFormatoFecha.dateFormat = "dd/MM/yyyy" 

     let nombre = nombreCalendario.text 
     let fin = setFormatoFecha.string(from: fechaFinCalendario.date) 
     let inicio = setFormatoFecha.string(from: fechaInicioCalendario.date) 

     //SE INSERTAN LOS DATOS LEIDOS. 
     calendario = Calendario(nombre: nombre!, fin: fin, inicio: inicio) 

     // Get the new view controller using segue.destinationViewController. 
     // Pass the selected object to the new view controller. 
    } 

    //MARK: METODOS PRIVADOS 

    private func actualizaEstadoBotonGuardar() { 
     //DESHABILITA EL BOTON DE GUARDAR CUANDO ESTA EN BLANCO *WIP* 
     let texto = nombreCalendario.text ?? "" 
     let tieneTexto = !texto.isEmpty 

     //WIP 
     if (!texto.isEmpty) { 
      if (fechaInicioCalendario.date >= fechaFinCalendario.date) { 
       botonGuardar.isEnabled = false 
      } else { 
       botonGuardar.isEnabled = true 
      } 
     } 
    } 

} 
+0

你似乎有一個錯字。 'ViewController'而不是'ViewController1'。 –

+0

你想傳遞'[Calendario]'對象還是隻傳遞'totalCalendarios' var? – nayem

+0

only totalCalendarios –

回答

0

讓我知道我錯了,你的代碼是一個有點混亂給我。 (我會編輯)

您的totalCalendarios1ViewController1的實例中的值。在我看來,您希望將此值傳遞給ViewController2,並將其轉換爲名爲totalCalendarios2的變量。

首先,你有一個(小)的錯誤:

let totalCalendarios2 = copiaCalendarios.totalCalendarios 

難道不該totalCalendarios1? (這是我對你的命名規則感到困惑的地方,希望這可能是一個語言問題,或者你簡化你的代碼到打錯字的地步。)

不管怎樣,這是一個小問題。 真實問題與您的segue代碼。這就是你要糾正的地方。


比方說,你有以下幾種:

ViewController1:

var totalCalendarios:Int = 0 

ViewController2

var totalCalendarios:Int = 0 

現在ViewController1這個variabl e被更新爲不同的值,可能是2017,並且您希望將此值傳遞給ViewController2。所有你需要的 - 只要你有一個定義賽格瑞 - 是:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    if segue.identifier == "MySegueName" { 
     if let vc = segue.destination as? ViewController2 { 
      vc.totalCalendarios = totalCalendarios 
     } 
    } 
} 

相比代碼發佈,最大的錯誤是鑄造你的目的地VC爲ViewController而不是ViewController2。我看到其他潛在的問題,但是你的變量不足以讓我知道它們是否也是一個問題。

總之:

  • 除非你根本無法保持變量名相同,有鑑於控制器之間的事物命名一樣沒有問題。事實上,它有助於他人理解你的代碼。
  • 如果您使用的是segue,則不需要實例化任何視圖控制器。但你應該轉換目標VC正確在準備(for segue :)
  • 鑄造後,只需傳遞變量。
+0

是的,我糾正了代碼,它是totalCalendarios1,對不起,我會嘗試你的代碼,thx:D –

0

我假設你的班級名稱是ViewController1,如你所說。沒關係。但你是如何獲得let totalCalendarios2 = copiaCalendarios.totalCalendarios?它是一個錯字還是你實際上在你的代碼中寫了這行?它應該是:

let totalCalendarios2 = copiaCalendarios.totalCalendarios1 

好吧,如果你真的想從一個屏幕數據傳遞到另一個屏幕(其實這是一個控制器到另一個控制器)如下:

  1. 您的第一個視圖控制器(從你想傳遞的地方),擁有你想傳遞的數據類型的屬性。爲您的情況:

    var totalCalendarios = 0 
    

    現在根據您的需要更新此totalCalendarios

  2. 將數據傳遞與segue,則需要在界面添加賽格瑞生成器(從源頭控制到目標控制器),並給予segue的名稱。比方說,CalenderSegue

  3. 在你的第二個視圖控制器(要在其中傳遞),你需要有精確的類型,你是從第一個傳遞數據的屬性。在你的情況下,它是Int。因此,在你的第二個視圖控制器聲明一個屬性:

    var totalCalendarios = 0 
    
  4. 現在使用這個

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
        if let identifier = segue.identifier, identifier = "CalenderSegue" { 
         let destino = segue.destination as? CalendarioViewController // here you have to use the exact name of your Second View Controller instead of ViewController 
         destino?.totalCalendarios = totalCalendarios 
        } 
    } 
    

編輯:1

CalendarioViewController類中刪除這些行(你不不需要爲您的CalendarioTableViewController創建對象)

let copiaCalendarios = CalendarioTableViewController() 
let totalCalendarios = copiaCalendarios.totalCalendarios 

一下添加到CalendarioViewController

var totalCalendarios = 0 

而且從上面使用prepare(for segue: UIStoryboardSegue, sender: Any?)方法。

但如果你只有一個賽格瑞,並且已經從 TableViewCellCalendarioViewController添加它,那麼你可以使用

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
    let destino = segue.destination as? CalendarioViewController // here you have to use the exact name of your Second View Controller instead of ViewController 
    destino?.totalCalendarios = totalCalendarios 
} 

編輯:2

你可能有問題與segue。從TableViewCell中刪除所有segue,然後將它們添加回來。如果你不知道該怎麼辦,看到這個image

+0

是的,我已經更正了代碼,它是totalCalendarios1,對不起,我會嘗試你的代碼,thx:D –

+0

我在segue的一段代碼中添加了一個打印語句,它打印var totalCalendarios,並顯示2(總的日曆加載),然後在calendarioViewController的viewDidLoad()中打印totalCalendarios,它表示0.結果如下: Total Calendarios(segue):2 Total Calendarios(CalendarioViewController):0 –

+0

@MartinHernandezPerez是否在'prepare(for:sender:)'方法中正確使用'destino?.totalCalendarios = totalCalendarios'? – nayem

相關問題