2014-10-10 9 views
5

저는 TableViewCell이 터치 될 때 순간적으로 불을 끄는 데 문제가 있습니다. 두 번째보기에 URL을 전달해야한다고 표시됩니다. 라벨에. i 스토리 보드에서 역동적으로 모든 셀 (즉, 올바른 단어 일 것입니다. 프로그래밍 방식으로 사람들을 보았습니다)을 작성합니다.보기 자체를 제외하고는 다른보기에 링크 할 객체가 없습니다. 제가 한. 그래서 첫 번째 뷰 컨트롤러를 두 번째 컨트롤러에 연결하고 segue를 수행하는 코드를 추가했습니다.Swift - Dynamic TableCell의 Segue

맞는지 확실하지 않습니다. 내 지식은 내가하고 싶은 것을 정확히 설명하지 않은 자습서에서 나옵니다.

두 개의보기 코드가 있습니다.

제 뷰

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 

     } 
    } 
} 

감사

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) 

    } 

초보기.

답변

2

두 번째보기 컨트롤러에 데이터를 전달하려면 첫 번째보기 컨트롤러에 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) 메서드를 구현해야하며 여기에서 segue.destinationViewController 개체를 통해 두 번째보기 컨트롤러에 모든 데이터를 전달해야합니다.

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

     } 
    } 

초 뷰 컨트롤러

override func viewDidLoad() { 
    super.viewDidLoad() 

    self.label.text = self.data 
} 

데이터 변수의 데이터를 얻기위한 코드 예

위한

는 제 뷰 컨트롤러의 속성으로 정의되어야한다.

+0

첫 번째 컨트롤러에서 두 번째보기 컨트롤러의 데이터 속성을 검색하는 방법은 무엇입니까? 제 1 뷰 제어기는 제 2 뷰 제어기가 갖는 특성을 알지 못한다. – DeepVinicius

+1

segue.destinationViewController를 SecondView 컨트롤러로 전송해야합니다. 내 대답에 필요한 편집을했다. –

관련 문제