2015-12-20 41 views
1

我正在編寫一個多步驟註冊流程,但無法獲得單元格標籤在每個視圖控制器之間傳遞。爲什麼這個值不會在我的ViewControllers之間傳遞?

這裏是從第一個的viewController的代碼:

class FirstVC: UIViewController, UITableViewDelegate { 

@IBOutlet weak var tableview: UITableView! 
var userGoalOptions = ["Lose Fat","Gain Muscle", "Be Awesome"] 
var selectedGoal: String = "" 


override func viewDidLoad() { 
    super.viewDidLoad() 
    self.title = "What Is Your Goal?" 

} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("Cell1")! as UITableViewCell 

    cell.textLabel?.text = userGoalOptions[indexPath.row] 

    return cell 
} 

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

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 

    let indexPath = tableView.indexPathForSelectedRow 
    let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell! 

    selectedGoal = currentCell.textLabel!.text! 

    } 

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
     if (segue.identifier == "secondSeque") { 

      let vc = segue.destinationViewController as! SecondVC 

      vc.userGoal = selectedGoal  
    } 
} 

的賽格瑞(secondSegue)連接到表視圖細胞在界面生成器

以我目的地的ViewController(VC)我有一個空userGoal變量,但是當我嘗試打印內容時,它什麼都不返回。

我知道這個問題的變體已經被問過無數次了,但我似乎無法找到(或者理解)我搞砸了。

回答

2

假設SEGUE被連接到該單元被作爲sender參數傳遞在界面生成器表視圖細胞在prepareForSegue

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
    if (segue.identifier == "secondSeque") { 
     let selectedIndexPath = tableView.indexPathForCell(sender as! UITableViewCell)! 
     let vc = segue.destinationViewController as! SecondVC 

     vc.userGoal = userGoalOptions[selectedIndexPath.row]  
} 

在這種情況下,不需要didSelectRowAtIndexPath,並且可以被刪除。


除此之外,它始終是更好的方式來從模型(userGoalOptions)比例如圖(表視圖細胞)檢索數據

let indexPath = tableView.indexPathForSelectedRow 
selectedGoal = userGoalOptions[indexPath.row] 

不要

let indexPath = tableView.indexPathForSelectedRow 
let currentCell = tableView.cellForRowAtIndexPath(indexPath!) as UITableViewCell! 
selectedGoal = currentCell.textLabel!.text! 
+0

謝謝你的回覆。 segue連接到界面生成器中的tableviewcell,並且我已經刪除了didSelectRowAtIndexPath。但是,標籤的內容仍然沒有傳遞到第二種觀點。 我已更新問題以添加您的假設 –

+1

設置斷點或插入'print'行來判斷方法是否被調用並觀察變量。這可能是一個錯字。在Interface Builder中檢查segue標識符。也許它是'secondSegue'而不是'secondSeque' – vadian

+0

Segue!== seque。我不知道你是怎麼想出來的,但是謝謝。我覺得自己像個傻瓜。你是絕地武士。 –

1

prepareForSegue不應該成爲表視圖函數的一部分,你已經將它複製到它永遠不會被調用的地方。將它移出並在其上放置一個斷點以查看它正在被調用。

相關問題