我试图通过使用Segue的更改行数来将数据从VC(GameCreatingView)传递到嵌入式TableView(PlayersTableView)的方法,但这似乎无效。
第一个文件:
class GameCreatingViewController: UIViewController {
var newGame = Game()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
newGame = Game()
newGame.playerBook?.NumberOfPlayers = 2
print(newGame.playerBook?.NumberOfPlayers)
for i in 1...6 {
newGame.playerBook?.players[i].number = i
if i <= 2 {
newGame.playerBook?.players[i].alive = true
} else {
newGame.playerBook?.players[i].alive = false
}
}
}
@IBOutlet weak var numberOfPlayers: UILabel!
@IBAction func changePlayers(_ sender: UIStepper) {
numberOfPlayers.text = String(Int(sender.value))
newGame.playerBook?.NumberOfPlayers = Int(sender.value)
performSegue(withIdentifier: SetNames, sender: Any?)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "StartGame" {
guard let destination = segue.destination as? PlayersTableViewController else { return }
guard let newGame = sender as? Game else { return }
let tableGame = newGame
destination.currentGame = tableGame
}
if segue.identifier == "SetNames" {
guard let destination = segue.destination as? GameViewController else { return }
guard let newGame = sender as? Game else { return }
let gameToPlay = newGame
destination.currentGame = gameToPlay
}
}
第二个文件:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
let numberOfRows = currentGame.playerBook?.NumberOfPlayers ?? 3
return currentGame.playerBook?.NumberOfPlayers ?? 3
print("Rows\(numberOfRows)")
}
行数不变,因此总是有3行。
答案 0 :(得分:0)
在ContainerView中嵌入另一个视图控制器时,将在加载父视图控制器时执行segue。您可以获取子视图控制器引用并像这样传递数据。
@IBAction func changePlayers(_ sender: UIStepper) {
numberOfPlayers.text = String(Int(sender.value))
newGame.playerBook?.NumberOfPlayers = Int(sender.value)
if let vc = self.childViewControllers.first(where: { $0 is PlayersTableViewController }) as? PlayersTableViewController {
vc.currentGame = self.newGame
vc.tableView.reloadData()
}
if let vc = self.childViewControllers.first(where: { $0 is GameViewController }) as? GameViewController {
vc.currentGame = self.newGame
vc.tableView.reloadData()
}
}