2014-10-10 13 views
5

Sto imparando rapidamente, e sto avendo problemi a cercare di sparare un seguito quando viene toccato un TableViewCell, che dovrebbe passare un URL a una seconda vista che per il momento solo un display in un'etichetta i Creare dinamicamente (ho visto persone che usano Programmaticamente, che è probabilmente la parola giusta) ogni singola cella, quindi, nello storyboard non ho alcun oggetto da collegare ad un'altra vista tranne la vista stessa ... e questo è cosa ho fatto. Quindi ho collegato il primo controller di visualizzazione al secondo e aggiunto il codice per eseguire il seguito.Swift - Segue su Dynamic TableCell

Non sono sicuro che se sia giusto, la mia conoscenza proviene da tutorial che non spiegavano esattamente cosa volevo fare.

laggiù c'è il codice delle due viste.

prima vista

import UIKit 

protocol sendInfoDelegate{ 

    func userDidEnterInfo(WhichInfo info : String) 

} 

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 

var tableData = [] 
@IBOutlet weak var redditListTableView: UITableView! 
var selectedCellURL : String? 
var delegate : sendInfoDelegate? = nil 



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

    // change the link to change the json source 

    getRedditJSON("http://www.reddit.com/.json") 
} 

// 
//Creates a connection via a task (networktask) then parses the json 
// 
func getRedditJSON(whichReddit : String){ 
    let mySession = NSURLSession.sharedSession() 
    let url: NSURL = NSURL(string: whichReddit) 
    let networkTask = mySession.dataTaskWithURL(url, completionHandler : {data, response, error -> Void in 
     var err: NSError? 
     var theJSON = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSMutableDictionary 
     let results : NSArray = theJSON["data"]!["children"] as NSArray 
     dispatch_async(dispatch_get_main_queue(), { 
      self.tableData = results 
      self.redditListTableView.reloadData() 
     }) 
    }) 
    networkTask.resume() 
} 

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

//needs to be implemented 

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

//creates the whole table 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell") 
    let redditEntry : NSMutableDictionary = self.tableData[indexPath.row] as NSMutableDictionary 
    cell.textLabel?.text = redditEntry["data"]!["title"] as? String 
    cell.detailTextLabel?.text = redditEntry["data"]!["author"] as? String 
    return cell 
} 

// action to be taken when a cell is selected 
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    let redditEntry : NSMutableDictionary = self.tableData[indexPath.row] as NSMutableDictionary 
    self.selectedCellURL = redditEntry["data"]!["url"] as? String 
    self.performSegueWithIdentifier("passInfo" , sender: indexPath) 
    println(self.selectedCellURL!) 

    if delegate != nil { 
     let information:String = self.selectedCellURL! 
     println("ciao") 
     delegate?.userDidEnterInfo(WhichInfo: information) 
     self.navigationController?.popViewControllerAnimated(true) 

    } 

seconda vista

import UIKit 




class WebPageController : UIViewController, sendInfoDelegate { 


    var infoFromSVC: String? 

    @IBOutlet weak var labelVC: UILabel! 


    func userDidEnterInfo(WhichInfo info: String) { 
     self.infoFromSVC = info 
     labelVC.text = infoFromSVC 

    } 

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

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
     if segue.identifier == "passInfo"{ 
      let firstVController : ViewController = segue.destinationViewController as ViewController 
      firstVController.delegate = self 

     } 
    } 
} 

Grazie.

risposta

2

Per passare qualsiasi dato al controller della seconda vista è necessario implementare il metodo prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) nel primo controller della vista e qui passare tutti i dati al secondo controller della vista tramite l'oggetto follow.destinationViewController.

ad esempio

// this method must be in first view controller 
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
     if segue.identifier == "passInfo" { 
      var secondViewController : SecondViewController = segue.destinationViewController as SecondViewController 

      var indexPath = self.tableview.indexPathForSelectedRow() //get index of data for selected row  

      secondViewController.data = self.dataArray.objectAtIndex(indexPath.row) // get data by index and pass it to second view controller 

     } 
    } 

Il codice per ottenere i dati al secondo controller di vista

override func viewDidLoad() { 
    super.viewDidLoad() 

    self.label.text = self.data 
} 

La variabile di dati deve essere definito come una proprietà del vostro secondo controller della vista.

+0

Come è possibile recuperare la proprietà dati del secondo controller di visualizzazione dal primo? il primo controller di visualizzazione non conosce quali proprietà ha il secondo controller di visualizzazione. – DeepVinicius

+1

È necessario inoltrare follow.destinationViewController al controller SecondView. Ho apportato le modifiche necessarie alla mia risposta –