简体   繁体   中英

Xcode: TableView cell to create ViewController

I've recently started using Xcode and Beginner to creating apps. I've come across something I'd like to implement but research hasn't been quite clear/complicated to understand.

I have a TableView with Days of Week and also a segmentedControl that duplicates these days 3 times. I'm wondering how I'm able to get user click to take me to an alternative ViewController depending on which day it is and what segment of the segmentedController is selected without having to create 21 viewcontrollers in the storyboard.

I've used a ViewController and made an outlet to a tableView for this setup.

具有segmentedController的TableView

You can have one viewcontroller which is basically a recipe for the viewcontroller you want to go to.

For example you want to show a viewcontroller with a label that states a combination of the number from the segmented control and the date which the user tapped on.

If you now create a ViewController which has a label in storyboard, the text on the label doesnt matter, you can use code to change the text to anything you would like.

In the tableviewcontroller you can use the didSelect delegate method of your tableview to present the viewcontroller and set the label to the values of the segmented control and the cell which is tapped.

I think you just need some more information about iOS and programming in general, therefore I suggest you watch the following iTunes U course:
https://itunes.apple.com/us/course/developing-ios-10-apps-with-swift/id1198467120
It has everything you need to know

in you tableview delegate method -> didSelectedRowAtIndexPath

you can simply write 
let vc = UIViewController()
/*
you can add informations here 
*/
present(vc, animated: true)

and inside this method you can use the indexPath to get the cell you've clicked

let cell = tableView.cellForRowAt(indexPath)

now you can get the information in this cell

Create a detail view controller with two variables (Ex - dayName and selectedSegmentIndex). And in your current viewController "tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)" push detailsViewController with these details like this

let objViewController: DetailsViewController? = UIStoryboard.mainStoryboard().instantiateViewController(withIdentifier: "DetailsViewController") as? DetailsViewController
    objViewController?.dayName = dayName
    objViewController?.selectedSegment = segmentControl.selectedSegmentIndex
    navigationController?.pushViewController(objViewController ?? UIViewController(), animated: true)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM