下面: -
导入UIKit
类ViewController:UIViewController,UIPickerViewDataSource,UIPickerViewDelegate { @IBOutlet弱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]
}
}
}
答案 0 :(得分:0)
您正在错误的地方添加委托方法。不要将选择器委托方法放在按钮操作中。
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]
}
}