arish tripathi arish tripathi -4 years ago 61
Swift Question

xcode is showing error compiling the codes

Here:-

import UIKit

class ViewController : UIViewController,UIPickerViewDataSource,UIPickerViewDelegate {
@IBOutlet weak var statePicker: UIPickerView!

@IBOutlet weak var statepickerbtn: UIButton!

let states = ["alaska","alabama","akansas","california","maine","new york"]

override func viewDidLoad() {
super.viewDidLoad()
statePicker.dataSource = self
statePicker.delegate = self
// Do any additional setup after loading the view, typically from a nib.
}

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

@IBAction func statebtnpressed(_ sender: Any) {

func numberOfComponents(in: <#T##UIPickerView#>)-> Int
{
return 1
}
func pickerView(<#T##pickerView: UIPickerView##UIPickerView#>, numberOfRowsInComponent: <#T##Int#>)->Int
{
return states.count
}


func pickerView(<#T##pickerView: UIPickerView##UIPickerView#>, titleForRow: <#T##Int#>, forComponent: <#T##Int#>) -> String?
{
return states[row]
}

}


}

Answer Source

You Are adding delegate methods on wrong place. Don't put pickers delegates methods inside button action.

class ViewController : UIViewController,UIPickerViewDataSource,UIPickerViewDelegate { 

   @IBOutlet weak var statepickerbtn: UIButton!
   @IBOutlet weak var statePicker: UIPickerView!
   let states = ["alaska","alabama","akansas","california","maine","new york"]

   override func viewDidLoad() {
    super.viewDidLoad()
    statePicker.dataSource = self
    statePicker.delegate = self
    // Do any additional setup after loading the view, typically from a nib.
   }

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

  @IBAction func statebtnpressed(_ sender: Any) { 
  //Do not place delegates method inside this action method. Instead of this use show hide procedure on picker view.

   }

public func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return states.count

}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return states[row]
}

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download