如何使用“完成”按钮制作UIPickerView?


72

我很难使用户点击UITextField时出现带有完成按钮的UIPickerView。到目前为止,这是我的代码。一切正常,但是当我点击文本字段时,出现键盘,而不是选择器。

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {


@IBOutlet var textField1: UITextField!

let pickerData = ["11", "12", "13"]





@IBAction func textButton(sender: AnyObject) {

    let picker: UIPickerView
    picker = UIPickerView(frame: CGRectMake(0, 200, view.frame.width, 300))
    picker.backgroundColor = .whiteColor()

    picker.showsSelectionIndicator = true
    picker.delegate = self
    picker.dataSource = self

    let toolBar = UIToolbar()
    toolBar.barStyle = UIBarStyle.Default
    toolBar.translucent = true
    toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1)
    toolBar.sizeToFit()

    let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Plain, target: self, action: "donePicker")
    let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action: "donePicker")

    toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
    toolBar.userInteractionEnabled = true

    textField1.inputView = picker
    textField1.inputAccessoryView = toolBar




}



override func viewDidLoad() {
    super.viewDidLoad()
    // 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.
}

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

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

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

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    textField1.text = pickerData[row]
}

func donePicker() {

    textField1.resignFirstResponder()

}




}

您在哪里调用textButton方法?
iAnurag

Answers:


135

将此代码添加到您viewDidLoad()的方法中

let picker: UIPickerView
picker = UIPickerView(frame: CGRectMake(0, 200, view.frame.width, 300))
picker.backgroundColor = .whiteColor()

picker.showsSelectionIndicator = true
picker.delegate = self
picker.dataSource = self

let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.tintColor = UIColor(red: 76/255, green: 217/255, blue: 100/255, alpha: 1)
toolBar.sizeToFit()

let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItem.Style.done, target: self, action: #selector(self. donePicker))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItem.Style.plain, target: self, action: #selector(self. donePicker))

toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.userInteractionEnabled = true

textField1.inputView = picker
textField1.inputAccessoryView = toolBar

它可能用于不同的线程。但是当我使用上面的示例完成操作时,未选择uipickerview项目。我怎么做?
vBaarathi '16

2
@iAnurag我想在点击按钮时显示选择器,然后从“选择器”中选择后进行选择,然后将其分配给按钮标题。因此,inputAccessoryView对于UIButton不起作用。还有其他解决方案吗?
Jayprakash Dubey

是否可以对齐工具栏右侧的按钮?
ndreisg

1
找到解决方案后,将以下内容添加为第一项:let spacer = UIBarButtonItem(barButtonSystemItem:.flexibleSpace,target:self,action:nil)
ndreisg,

如果您可以将答案更新为快速4或5,那就太好了
Yash Bedi

43

我认为最好创建一个自定义类以从控制器中删除代码。

Swift 4/5示例

import Foundation
import UIKit

protocol ToolbarPickerViewDelegate: class {
    func didTapDone()
    func didTapCancel()
}

class ToolbarPickerView: UIPickerView {

    public private(set) var toolbar: UIToolbar?
    public weak var toolbarDelegate: ToolbarPickerViewDelegate?

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.commonInit()
    }

    private func commonInit() {
        let toolBar = UIToolbar()
        toolBar.barStyle = UIBarStyle.default
        toolBar.isTranslucent = true
        toolBar.tintColor = .black
        toolBar.sizeToFit()

        let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(self.doneTapped))
        let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(self.cancelTapped))

        toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
        toolBar.isUserInteractionEnabled = true

        self.toolbar = toolBar
    }

    @objc func doneTapped() {
        self.toolbarDelegate?.didTapDone()
    }

    @objc func cancelTapped() {
        self.toolbarDelegate?.didTapCancel()
    }
}

用法示例:

class MyViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!
    fileprivate let pickerView = ToolbarPickerView()
    fileprivate let titles = ["0", "1", "2", "3"]

    override func viewDidLoad() {
        super.viewDidLoad()

        self.textField.inputView = self.pickerView
        self.textField.inputAccessoryView = self.pickerView.toolbar

        self.pickerView.dataSource = self
        self.pickerView.delegate = self
        self.pickerView.toolbarDelegate = self

        self.pickerView.reloadAllComponents()
    }
}

extension MyViewController: UIPickerViewDataSource, UIPickerViewDelegate {

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

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

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

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        self.textField.text = self.titles[row]
    }
}

extension MyViewController: ToolbarPickerViewDelegate {

    func didTapDone() {
        let row = self.pickerView.selectedRow(inComponent: 0)
        self.pickerView.selectRow(row, inComponent: 0, animated: false)
        self.textView.text = self.titles[row]
        self.textField.resignFirstResponder()
    }

    func didTapCancel() {
        self.textField.text = nil
        self.textField.resignFirstResponder()
    }
}

它可能更好地为didTapDonedidTapCancel方法在通过ToolbarPickerView实例; 像func didTapDone(_ picker: ToolbarPickerView)
mixtly87

20

UIPickerView有完成按钮吗?迅捷4

步骤1:在ViewController中添加一个名为txt_pickUpData的textFiled,并提供IBOutlet连接和委托。还可以使用一个UIDatePicker变量。并选择一个在字符串上显示的值的数组。

@IBOutlet weak var txt_pickUpData: UITextField!
var myPickerView : UIPickerView!
var pickerData = ["Hitesh Modi" , "Kirit Modi" , "Ganesh Modi" , "Paresh Modi"]

步骤2:还添加UIPickerView和UITextFiled的委托。

class ViewController: UIViewController , UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate{

第3步:函数pickUp使用ToolBar创建UIPickerView。

func pickUp(_ textField : UITextField){

// UIPickerView
self.myPickerView = UIPickerView(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216))
self.myPickerView.delegate = self
self.myPickerView.dataSource = self
self.myPickerView.backgroundColor = UIColor.white
textField.inputView = self.myPickerView

// ToolBar
let toolBar = UIToolbar()
toolBar.barStyle = .default
toolBar.isTranslucent = true
toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
toolBar.sizeToFit()

// Adding Button ToolBar
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(ViewController.doneClick))
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(ViewController.cancelClick))
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
textField.inputAccessoryView = toolBar

 }

步骤4:添加UIPickerView的委托和数据源方法,以在UIPickerView轮上显示数据。

//MARK:- PickerView Delegate & DataSource
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
 }
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerData.count
 }
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickerData[row]
  }
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.txt_pickUpData.text = pickerData[row]
 }
 //MARK:- TextFiled Delegate

 func textFieldDidBeginEditing(_ textField: UITextField) {
self.pickUp(txt_pickUpData)
 }

步骤5:在工具栏中添加两个按钮方法。一个是doneClick,另一个是cancelClick。这是关闭UIPickerView。

func doneClick() {
  txt_pickUpData.resignFirstResponder()
 }
func cancelClick() {
  txt_pickUpData.resignFirstResponder()
}

步骤6:在UITextField委托方法中调用pickUp函数。

func textFieldDidBeginEditing(_ textField: UITextField) {
self.pickUp(txt_pickUpData)
}

只需复制并粘贴您的代码即可。


请注意,在Swift 4中,您需要@objcdoneClickcancelClick函数之前添加。
口味像土耳其,土耳其

2
谢谢您这么完整的答案!我还注意到,我们应该记住将ViewController设置为textField委托-txt_pickUpData.delegate = self。我完成了故事板
Vitya Shurapov '18 -10-5

8

人们似乎在将代码用于其他问题,以问问VBaarathi 提出的问题

在Swift3中

let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(donePicker))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.plain, target: self, action: #selector(donePicker))

然后,您可以将以下内容放入同一swift文件中

func donePicker (sender:UIBarButtonItem)
{
     // Put something here
}

3

Swift 3x:

很棒的答案已经给出了,但是这里是不同的方法,只做一个,pickerView然后给inputView和就可以了inputAccessoryView

YOUR_TEXTFIELD_NAME.inputView = picker


func addKeyboardToolBar() {

  var nextButton: UIBarButtonItem?
  var keyboardToolBar = UIToolbar(frame: CGRect(x: CGFloat(0), y: 
  CGFloat(0), width: CGFloat(pickerView.frame.size.width), height: CGFloat(25)))
  keyboardToolBar.sizeToFit()
  keyboardToolBar.barStyle = .default
  daysHourTextField.inputAccessoryView = keyboardToolBar
  nextButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(self.textFieldShouldReturn))
  keyboardToolBar.items = [UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), nextButton]

}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.