Choose which ViewController to switch to by using Picker View - ios

I am creating a restaurant app, in which the user could select which restaurant they would like to do on the first screen. After they've made their selection the user should press the begin button and it will take it to that View Controller
I have no idea how to get started, any help would be appreciated.

Set label text in picker didselect delegate . then on button action method decide which vc to open on the basis of label text.

Used button action is Done Button that we embed with picker to make final selection.
Use the following code: Works fine
import UIKit
class PickerViewController: UIViewController,UIPickerViewDataSource, UIPickerViewDelegate {
#IBOutlet weak var pickerVieww: UIPickerView!
var viewControllerArray = [String]()
var value = Int()
override func viewDidLoad() {
super.viewDidLoad()
pickerVieww.delegate = self
pickerVieww.dataSource = self
viewControllerArray = ["controller1","controller2","controller3"]
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return viewControllerArray.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return viewControllerArray[row]
}
func pickerView(_ pickerView: UIPickerView,didSelectRow row: Int,inComponent component: Int)
{
if(row == 0) {
value = 0
}
else if(row == 1) {
value = 1
}
else{
value = 2
}
}
#IBAction func swicthToController(_ sender: Any) {
if value == 0{
let vc = self.storyboard?.instantiateViewController(withIdentifier: "first") as! asasasViewController
self.present(vc, animated: true, completion: nil)
}
if value == 1{
let vc = self.storyboard?.instantiateViewController(withIdentifier: "second") as! secondViewController
self.present(vc, animated: true, completion: nil)
}
if value == 2{
let vc = self.storyboard?.instantiateViewController(withIdentifier: "third") as! thirdViewController
self.present(vc, animated: true, completion: nil)
}
}
}

Related

Linking a UIPickerView row title to a new view controller

I have a UIPickerView with some rows each having a title. What I want is when one clicks on a title, a new view controller specific to that title is linked to just like how clicking a button takes me to a new VC. How can I do that with a row title in a picker view?
I am trying to drag a specific row into the view controller but the whole picker get selected.
You can set pickerView delegate and after you can push viewController
Example code:
class ViewController: UIViewController {
#IBOutlet private weak var pickerView: UIPickerView!
struct PickerData {
let viewControllerId: String
let storyboardId: String
let title: String
}
private var pickersData: [PickerData] = []
override func viewDidLoad() {
super.viewDidLoad()
loadData()
pickerView.delegate = self
pickerView.dataSource = self
}
private func loadData() {
pickersData.append(
ViewController.PickerData(viewControllerId: "ViewController1", storyboardId: "Main", title: "Foo")
)
pickersData.append(
ViewController.PickerData(viewControllerId: "ViewController1", storyboardId: "Main", title: "Bar")
)
}
private func createViewController(from index: Int) -> UIViewController {
let model = pickersData[index]
let viewController = UIStoryboard(name: model.storyboardId, bundle: nil).instantiateViewController(withIdentifier: model.viewControllerId)
return viewController
}
private func pushViewController(viewController: UIViewController) {
// If Navigation
navigationController?.pushViewController(viewController, animated: true)
// If present
//present(viewController, animated: true, completion: nil)
}
}
extension ViewController: UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickersData.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickersData[row].title
}
}
extension ViewController: UIPickerViewDelegate {
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
pushViewController(viewController: createViewController(from: row))
}
}
#IBOutlet weak var myPickerView: UIPickerView!
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
performSegue(withIdentifier: "segue\(row)", sender: nil)
}
drag the segues from your view, not the pickerView

How to compare selected UIPickerView row element to Array element?

import UIKit
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
#IBOutlet weak var categoryFactsPincker: UIPickerView!
#IBOutlet weak var randomFactLabel: UILabel!
This is my array of my UIPickerView
let categoryFactsArray = ["Interesting Facts", "Fun Facts", "Nutrition Facts", "Funny Facts", "Unbelievable Facts", "Did You Know", "Animal Facts", "Mind Blowing Facts", "Weird Facts"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
categoryFactsPincker.delegate = self
categoryFactsPincker.dataSource = self
}
I would like to use this button to compare array element and UIPickerView selected for print different categories
#IBAction func buttonPressed(_ sender: UIButton) {
if categoryFactsArray[row] == 0 {
updateInterestingFacts()
}else if categoryFactsPincker.selectedRow(inComponent: 1){
}
}
func updateInterestingFacts(){
let random = interestingFactsArray[Int(arc4random_uniform(UInt32(interestingFactsArray.count)))]
// randomFactLabel.text = random
let alert = UIAlertController(title: "Random Fact", message: "\(random)", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return categoryFactsArray.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return categoryFactsArray[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
categoryFactsArray[row]
}
}
try this
#IBAction func buttonPressed(_ sender: UIButton) {
if categoryFactsPincker.selectedRow(inComponent: 0) == 0 {
updateInterestingFacts()
}else{
let categorySelected = categoryFactsArray[categoryFactsPincker.selectedRow(inComponent: 0)]
print(categorySelected)
}
}
this print should show the selected value, so you can use to compare, or whatever you need
At the end I fixed it with this code:
#IBAction func buttonPressed(_ sender: UIButton) {
if Int(categoryFactsPincker.selectedRow(inComponent: 0)) == 0 {
updateInterestingFacts()
}else if Int(categoryFactsPincker.selectedRow(inComponent: 0)) == 1 {
updateFunFacts()
}else if Int(categoryFactsPincker.selectedRow(inComponent: 0)) == 2{
updateNutritionFacts()
}else if Int(categoryFactsPincker.selectedRow(inComponent: 0)) == 3{
updateFunnyFacts()
}else if Int(categoryFactsPincker.selectedRow(inComponent: 0)) == 4{
updateUnbelievableFacts()
}else if Int(categoryFactsPincker.selectedRow(inComponent: 0)) == 5{
updateDidYouKnowFacts()
}else if Int(categoryFactsPincker.selectedRow(inComponent: 0)) == 6{
updateAnimalFacts()
}else if Int(categoryFactsPincker.selectedRow(inComponent: 0)) == 7{
updateMindBlowingFacts()
}else if Int(categoryFactsPincker.selectedRow(inComponent: 0)) == 8{
updateWeirdFacts()
}
}

picker view with button to go to next page

I'm trying to do a pickerView and a button which when you choose your option in pickerView it goes to the relevant page.
So far I've got to the point when you choose the option in picker view it goes to the relevant page, but what I want is choose and then click on the button to go to the page.
import UIKit
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
#IBOutlet weak var pickerView: UIPickerView!
var selection = ["Page 1", "Page 2", "Page 3"]
override func viewDidLoad() {
super.viewDidLoad()
pickerView.dataSource = self
pickerView.delegate = self
}
#IBAction func SelectionBtn(_ sender: Any) {
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return selection.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
let selected = selection[row]
return selected
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if (row == 0) {
performSegue(withIdentifier: "red", sender: self)
}
else if (row == 1) {
performSegue(withIdentifier: "blue", sender: self)
}
else {
performSegue(withIdentifier: "green", sender: self)
}
}
}
Take an extra variable to store information on regarding which row you have selected.
var rowSelected:Int! = -1
Store the selected row to this variable.
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
rowSelected = row
}
During button action check the variable to perform desired Segue.
#IBAction func actSegue(sender:Any){
if row == 0 {
performSegue(withIdentifier: "red", sender: self)
}...
....
}
You can get the row selected with :pickerView.selectedRow(inComponent: 0)
#IBAction func SelectionBtn(_ sender: Any) {
let rowSelected = pickerView.selectedRow(inComponent: 0)
if (rowSelected == 0) {
performSegue(withIdentifier: "red", sender: self)
}
else if (rowSelected == 1) {
performSegue(withIdentifier: "blue", sender: self)
}
else {
performSegue(withIdentifier: "green", sender: self)
}
}

How to navigate between two viewcontrollers using a UIPickerview

I am trying to navigate between two viewcontrollers using a UIPickerview, so i first learned how to use didSelectRow to change the title of a label and then i tried using some code to navigate to another viewcontroller but that didn't work.
The code that i used was:
import UIKit
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
#IBOutlet var label: UILabel!
#IBOutlet var pickerView: UIPickerView!
var food = ["hello", "hi", "hey"]
var placementAnswer = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
pickerView.delegate = self
pickerView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
public func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return food.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return food[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
placementAnswer = row
}
#IBAction func labelChanged(sender: UIButton) {
if (placementAnswer == 0){
}else if (placementAnswer == 1){
let view2 = self.storyboard?.instantiateViewControllerWithIdentifier("view2") as! ViewController2
self.navigationController?.pushViewController(view2, animated: true)
}else if (placementAnswer == 2){
}
}
}
As paranoidcoder pointed out I'm not sure your labelChanged method is getting called, which could be the problem with your existing code.
I'm assuming you want to change the view controller after a certain row is selected in the picker view. Putting the if statement to change views in didSelectRow would make the most sense in that case.
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
placementAnswer = row // unnecessary variable
if (placementAnswer == 0){}
else if (placementAnswer == 1)
{
let view2 = self.storyboard?.instantiateViewControllerWithIdentifier("view2") as! ViewController2
self.navigationController?.pushViewController(view2, animated: true)
}
else if (placementAnswer == 2) {}
}

Swift - Programmatically create and display UIPickerView when BarButtonItem is pressed

Initially I wanted to add a hidden UIPickerView onto the Main.storyboard alongside my existing UISearchBar and when a BarButtonItem is clicked, the UIPickerView should be displayed; but it appears I cannot have them both at once in a given space.
So instead, my best alternative was to create it programmatically. I've followed existing tutorials (http://sourcefreeze.com/ios-uipickerview-example-using-swift/) and similar questions (Programmatically Create and Show UIPickerView) and seems like I do (?) have a UIPickerView as the description of it is being printed and I get the following:
<UIPickerView: 0x7f86425b1fb0; frame = (100 100; 100 162); layer = <CALayer: 0x7f8642543a20>>
Here is part of my current code which may be of help:
AnimalTableViewController.swift
import UIKit
class AnimalTableViewController: UITableViewController, UINavigationControllerDelegate, UISearchBarDelegate, UISearchDisplayDelegate, UISearchResultsUpdating, UIPickerViewDelegate, UIPickerViewDataSource {
#IBOutlet var segmentedSortOption: UISegmentedControl!
var array : NSArray = Animal.animalStruct.jsonResult["animal"] as NSArray
var filteredArray = [[String:AnyObject]]()
var timer = NSTimer()
var counter:Int = 1
var typePickerView: UIPickerView = UIPickerView()
#IBOutlet var typeBarButton: UIBarButtonItem!
var resultSearchController = UISearchController()
var indexArray:String!
#IBAction func refresh(sender: AnyObject) {
self.tableView.reloadData()
println("refreshed")
}
override func viewDidLoad() {
super.viewDidLoad()
self.typePickerView.hidden = true
self.typePickerView.dataSource = self
self.typePickerView.delegate = self
self.typePickerView.frame = CGRectMake(100, 100, 100, 162)
self.typePickerView.backgroundColor = UIColor.blackColor()
self.typePickerView.layer.borderColor = UIColor.whiteColor().CGColor
self.typePickerView.layer.borderWidth = 1
timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: Selector("result"), userInfo: nil, repeats: true)
self.resultSearchController = ({
let controller = UISearchController(searchResultsController: nil)
controller.searchResultsUpdater = self
controller.dimsBackgroundDuringPresentation = false
controller.searchBar.sizeToFit()
self.tableView.tableHeaderView = controller.searchBar
return controller
})()
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return array.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return array[row]["type1"] as String
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
typeBarButton.title = array[row]["type1"] as? String
typePickerView.hidden = false
}
func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
return 36.0
}
func pickerView(pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 36.0
}
#IBAction func typePickerViewSelected(sender: AnyObject) {
typePickerView.hidden = false
println(typePickerView.description)
}
}
Please could you help me display the programmatically created UIPickerView when the BarButtonItem is pressed? If you have any more questions, please do ask.
Many thanks.
You never add the pickerView as a subview of the ViewController, which you can do in viewDidLoad() since you're hiding it. Then when you unhide it your view should be there.
EDIT: Added Code
override func viewDidLoad() {
super.viewDidLoad()
self.typePickerView.hidden = true
//other pickerView code like dataSource and delegate
self.view.addSubview(pickerView) //will add the subview to the view hierarchy
}
With the above code, now when you unhide it on button press the view will show up.

Resources