Very simple scenario with lots of posts on this, but I'm still stuck. I have a UITableView
that is embedded in a UINavigationController
There is a final UIViewController
that is supposed to be presented when the UITableViewCell
is selected. When I wire all of this up, nothing happens on the row selection.
I can get the detail view to be presented by usind didSelectRowAtIndexPath
and referencing the segue by its id. However, there is no back button when I do this.
class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableview: UITableView!
var configJson: JSON = []
var config: [Tab] = []
override func viewDidLoad() {
super.viewDidLoad()
parseConfig()
}
func parseConfig() {
let configParser = ConfigParser(configJson: configJson)
config = configParser.parse()
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.config.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let tab = self.config[indexPath.row]
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text = tab.title
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "contentSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "contentSegue") {
let nextVC = segue.destination as? ContentViewController
let indexPath = self.tableview.indexPathForSelectedRow
let tab = self.config[(indexPath?.row)!]
nextVC?.tab = tab
}
}
}
A couple of other notes: 1. My cell identifer is set to 'cell' in the IB
2. My segue is set to 'show' with a identifier of 'contentSegue' in the IB
3. The segue is from the prototype cell to the Content View Controller.
I'm at a total loss. Can anyone help? Thanks.
Are you sure you've set this up as a selection segue, and not an accessory action? You can check this by ctrl clicking on the cell in the storyboard - make sure your triggered segue is selection.
Also…
As you've added the segue in your storyboard, there's no need to fire it in didSelectRowAt
- so you can remove that func.
And, to remove your reliance on a string comparison (and remove a force unwrapped optional), try this…
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let nextVC = segue.destination as? ContentViewController,
let cell = sender? as UITableViewCell,
let indexPath = tableview.indexPath(for: cell) {
let tab = self.config[indexPath.row]
nextVC.tab = tab
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.