Swift-将数据从多节tableview传递到ViewController

时间:2015-08-03 14:04:26

标签: ios iphone uitableview

我有一个两节的tableview(见下图)

enter image description here

当我点击行" A"时,另一个桌面视图显示字母" A"

enter image description here

当我点击行" B"时,另一个桌面视图显示字母" B"

enter image description here

我怎样才能通过这封信" C"当我点击C行时,到另一个tableview?

这是我在TableView中的代码: 导入UIKit

类manhinh1:UITableViewController {

var UserDefault:NSUserDefaults!
var array:[[String]]!
override func viewDidLoad() {
    super.viewDidLoad()

    UserDefault = NSUserDefaults()
    array = [["A","B"],["C","D","E"]]

}

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

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return array.count
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    if section == 0 {
    return array[0].count
    }
    if section == 1 {
    return array[1].count
    }
    return 1
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell

    if indexPath.section == 0 {
    cell.textLabel?.text = array[0][indexPath.row]
    }
    if indexPath.section == 1 {
    cell.textLabel?.text = array[1][indexPath.row]
    }
    // Configure the cell...

    return cell
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    var row = self.tableView.indexPathForSelectedRow()!.row

    UserDefault.setObject(array[0][row], forKey: "selected")
}

}

这是第二个视图中的代码: 导入UIKit

类ViewController:UIViewController {

var UserDefault:NSUserDefaults!
@IBOutlet weak var lbldata: UILabel!
override func viewDidLoad() {
    super.viewDidLoad()
    UserDefault = NSUserDefaults()
    // Do any additional setup after loading the view, typically from a     }
    lbldata.text = UserDefault.objectForKey("selected") as! String
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

我在prepareForSegue中尝试了一些代码,但它没有用。我希望你们能告诉我一个方法。感谢

1 个答案:

答案 0 :(得分:1)

您必须获取行和部分才能访问多维数组。然后获取segue的目标视图控制器,并将数组中的相应值分配给UserDefault属性:

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    var row = self.tableView.indexPathForSelectedRow()!.row
    var section = self.tableView.indexPathForSelectedRow()!.section

    var destinationViewController = segue.destinationViewController as! ViewController 

    destinationViewController.UserDefault.setObject(array[section][row], forKey: "selected")
}