PikerView with ToolBar Demo

//  ViewController.swift
//  PikerViewToolBarPractice

import UIKit

class ViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate,UIToolbarDelegate {

    @IBOutlet var txtCITY: UITextField!
    
    let Pikerview = UIPickerView()
    
    var arrPiker = [String] ()
    
    var citydata = String()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        Pikerview.delegate = self
        Pikerview.dataSource = self
        // Do any additional setup after loading the view, typically from a nib.
         arrPiker.append("aa")
         arrPiker.append("bb")
         arrPiker.append("cc")
         arrPiker.append("dd")
         arrPiker.append("ee")
         arrPiker.append("ff")
         arrPiker.append("gg")
        
        PikerValueChanged()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return arrPiker.count
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return arrPiker[row]
    }
    
    func PikerValueChanged()
    {
        let toolbar = UIToolbar()
        toolbar.sizeToFit()
        
        let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        
        let DoneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(DonebuttonPressed))
        
        let CandsleButton = UIBarButtonItem(title: "Cansle", style: .plain, target: self, action: #selector(CansleButtonPressed))
        
        let lblTitle = UILabel()
        lblTitle.frame = CGRect(x: 0, y: 0, width: 150, height: 30)
        lblTitle.text = "Select City"
        lblTitle.textAlignment = .center
        lblTitle.backgroundColor = UIColor.gray
        
        
        let titleButton = UIBarButtonItem(customView: lblTitle)
        
        toolbar.setItems([CandsleButton,spaceButton,titleButton,spaceButton,DoneButton], animated: true)
        txtCITY.inputView = Pikerview
        txtCITY.inputAccessoryView = toolbar
        
    }
    func DonebuttonPressed()
    {
       txtCITY.text = citydata
    txtCITY.resignFirstResponder()
    }
    
    func CansleButtonPressed ()
    {
        txtCITY.resignFirstResponder()
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
    {
        citydata = arrPiker[row]
    }

}


Comments