2016-08-13 57 views
1

我有兩個視圖控制器。第二個視圖控制器託管一個具有自定義單元的表視圖,該單元展開回第一個視圖控制器併發送與該單元關聯的數據。Swift - Unwind segue傳回零值?

在第二個視圖控制器類中,我實現了didSelectRowAtIndexPath並測試瞭解正確的項是否存儲在類屬性中。它正確存儲可選值,但是當我嘗試在第一個視圖控制器中使用該值時,該屬性將nil輸出到控制檯。

// First view controller 

@IBAction func unwindActivitiesVCCellTapped(segue: UIStoryboardSegue) 
{ 
    // table view cell tapped 

    guard let activitiesVC = segue.sourceViewController as? ActivitiesVC else { return } 

    print(activitiesVC.activityPerforming) // Displays nil in console output 

    if let activityPerforming = activitiesVC.activityPerforming // thus this does not get called 
    { 
     activityPerformingButton.titleLabel?.text = activityPerforming 
    } 
} 

// Second View Controller 

class ActivitiesVC: UIViewController 
{ 
    @IBOutlet weak var activitiesTableView: UITableView! 

    let activityTitles = [ "Walk" , "Run ", "Cycle", "Mountain Bike" ] 

    var activityPerforming: String? 

    override func viewDidLoad() 
    { 
     super.viewDidLoad() 

     activitiesTableView.dataSource = self 
     activitiesTableView.delegate = self 
    } 
} 

extension ActivitiesVC: UITableViewDelegate 
{ 
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) 
    { 
     activityPerforming = activityTitles[ indexPath.row ] 
     print(activityPerfoming) // displays optional value I want 
    } 
} 

// Custom Cell 

class ActivityCell: UITableViewCell 
{ 

    @IBOutlet weak var imageLabel : UILabel! 
    @IBOutlet weak var activityLabel : 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 
    } 
} 

該屬性出現爲零的原因是什麼,我該如何解決這種情況?

回答

1

我懷疑你的展開順序直接連接到你的UITableViewCell,所以它被調用之前觸發didSelectRowAtIndexPath

爲了解決這個問題,將代碼didSelectRowAtIndexPathprepareForSegue

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
    if let indexPath = activitiesTableView.indexPathForSelectedRow { 
     activityPerforming = activityTitles[ indexPath.row ] 
     print(activityPerfoming) // displays optional value I want 
    } 
} 
+0

究竟是什麼固定的問題。我非常感謝! – lifewithelliott

+0

不客氣!我很高興能夠提供幫助。 – vacawama