如何使用按钮从pickerview中选择数据(swift4)

时间:2017-12-25 20:21:20

标签: ios select button swift4 picker

我想使用按钮从我的选择器视图中选择数据。目前我的代码使用按钮来关闭选择器视图,但该按钮不会从选择器视图中选择任何内容。选择某些内容的唯一方法是使用选择器视图滚动。如何使用我的按钮作为提取器视图提交数据的唯一方法?

   override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    picker.delegate = self
    picker.dataSource = self
    for textFieldObject in theScoreRound
    {
        textFieldObject.inputView = picker

        let toolbar = UIToolbar(frame: CGRect(x: 0, y: UIApplication.shared.statusBarFrame.height, width: view.bounds.width, height: 44))

        var items = [UIBarButtonItem]()

        items.append( UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil) )
        items.append( UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(self.doneAction)) )
        items.append( UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: self, action: nil) )

        toolbar.items = items


        let fs = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
        let db = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(self.doneAction))
        toolbar.setItems([fs,db],animated: false)
        textFieldObject.inputAccessoryView = toolbar



    }}
   @objc func doneAction(){

    view.endEditing(true)

}
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return numberX.count
}

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

public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    for textField in theScoreRound {
        if textField.isEditing {
            textField.text = numberX[row]

        }
    }

    self.view.endEditing(false)
}

@IBAction func enterScore(_ sender: Any) {
    var total = 0
    for view in theScoreRound {
        if let text = view.text, let num = Int(text) {
            total += num

        }
    }
    fighterAScore.text = String(total)

}

1 个答案:

答案 0 :(得分:0)

您需要使用UIPickerView selectedRow(inComponent: <#T##Int#>)方法,在这种情况下传递组件编号0,因为在UIPickerDataSource中,您在numberOfComponents方法中返回1 < / p>

示例代码

@IBAction func pickerDataAction(_ sender: Any) {
   let selectedRow = self.pickerView.selectedRow(inComponent: 0)
   let desiredValue = numberX[selectedRow]
}