web-dev-qa-db-ja.com

完了ボタンでUIPickerViewを作成する方法は?

ユーザーが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()

}




}
61
Alberto O.

メソッドの代わりにこのコードを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.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
117
iAnurag

[完了]ボタンのあるUIPickerView?Swift4

ステップ1:txt_pickUpDataという名前の1つのtextFiledをViewControllerに追加し、IBOutlet接続とデリゲートを提供します。また、1つの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:ToolBarでUIPickerViewを作成するための関数pickUp。

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:ツールバーにある2つのボタンメソッドを追加します。 1つはdoneClick、もう1つはcancelClickです。これはUIPickerViewを閉じます。

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

ステップ6:UITextFieldデリゲートメソッドでpickUp関数を呼び出します。

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

コードをコピーして貼り付けてください。

15
Nil Rathod

コントローラからコードを削除するには、カスタムクラスを作成する方が良いと思います。

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()
    }
}
14
Eridana

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
}
8
Longmang

Swift 3x:

素晴らしい答えはすでに与えられていますが、異なるアプローチがあります。pickerViewを作成し、inputViewinputAccessoryViewを次のように指定します。

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]

}
3
Anurag Sharma