this is my code
- #IBOutlet weak var txt1: UITextField!
#IBOutlet weak var txt2: UITextField!
#IBOutlet weak var txt3: UITextField!
#IBOutlet weak var txt4: UITextField!
#IBOutlet weak var txt5: UITextField!
#IBOutlet weak var txt6: UITextField!
#IBOutlet weak var txt7: UITextField!
#IBOutlet weak var picker: UIPickerView!
var category = ["Male", "Female", "Others"]
let datePicker = UIDatePicker()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
picker.isHidden = true
txt3.delegate = self
self.txt3.inputView = picker
//txt3.inputView = category[row]
}
// returns the # of rows in each component..
func pickerView(pickerView: UIPickerView!, numberOfRowsInComponent component: Int) -> Int{
return category.count
}
func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String! {
return category[row]
}
func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int)
{
txt3.text = category[row]
// category.isHidden = true;
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
if textField == txt3 {
//resignFirstResponder()
//picker.isHidden = true
}
return true
}
}
#IBAction func txt3(_ sender: Any) {
func showDatePicker(){
//Formate Date
datePicker.datePickerMode = .date
//ToolBar
let toolbar = UIToolbar();
toolbar.sizeToFit()
//done button & cancel button
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.bordered, target: self, action:
Selector(("donedatePicker")))
//let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
// let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.bordered, target: self, action:
Selector("cancelDatePicker"))
toolbar.setItems([doneButton], animated: false)
// add toolbar to textField
txt3.inputAccessoryView = toolbar
// add datepicker to textField
txt3.inputView = datePicker
}
func donedatePicker(){
//For date formate
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy"
txt3.text = formatter.string(from: datePicker.date)
//dismiss date picker dialog
self.view.endEditing(true)
}
func cancelDatePicker(){
//cancel button dismiss datepicker dialog
self.view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
Blockquote
override func viewDidLoad(){
super.viewDidLoad()
picker.isHidden = true
txt3.delegate = self
//self.txt3.inputView = picker // don't do this
self.txt3.inputView = datePicker // do like this.
let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.doneButton))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.doneButton)
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
txt3.inputAccessoryView = toolBar
}
func doneButton(){
let selectedDate = datePicker.date
print(selectedDate)
txt3.resignFirstResponder()
}
It will automatically open the date picker.
txt3.inputView = picker
and remove
picker.isHidden = true
This should do the trick!
first, you add this..
txt3.inputView = picker
then you add
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
if textField == txt3 {
picker.isHidden = false
}
else {
picker.isHidden = true
}
return true
}
Related
I am attempting to add "done" and "cancel" buttons in a toolbar above a pickerView that will be used to change the value of a label. The label should only be changed when "done" is clicked not when UIPicker received rowSelected.
I can't understand why my "done" and "cancel" buttons do not show above my picker? I'm sure this will be marked as duplicate, but I've done something very similar in Swift 4, and this doesn't seem to work in Swift 5.
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource {
#IBOutlet weak var freq: UILabel!
var freqOptions = ["Hz", "kHz", "MHz"]
var freqPicker = UIPickerView()
#IBOutlet weak var freqTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
freqPicker = UIPickerView( frame: CGRect(x: 0, y: 100, width: self.view.frame.width, height: 216) )
freqPicker.backgroundColor = UIColor.white
freqPicker.delegate = self
freqPicker.dataSource = self
freqPicker.isHidden = true
let toolBar = UIToolbar()
let cancelItem = UIBarButtonItem(
title: "Cancel",
style: .plain,
target: self,
action: #selector(cancelFreqInput)
)
let middleItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneItem = UIBarButtonItem(
title: "Done",
style: .done,
target: self,
action: #selector(confirmFreqInput)
)
toolBar.setItems( [cancelItem, middleItem, doneItem], animated : false )
toolBar.sizeToFit()
view.addSubview(freqPicker)
let freqTap = UITapGestureRecognizer(target: self, action: #selector(freqTap(gestureReconizer:)))
freq.addGestureRecognizer(freqTap)
freqTextField.inputView = freqPicker
freqTextField.inputAccessoryView = toolBar
freqTextField.isHidden = true
freq.isUserInteractionEnabled = true
}
#objc func cancelFreqInput() {
freqTextField.resignFirstResponder()
freq.text = "Hz"
freqTextField.isHidden = true
}
#objc func confirmFreqInput() {
freqTextField.resignFirstResponder()
freqTextField.isHidden = true
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return freqOptions.count
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
freq.text = freqOptions[row]
self.view.endEditing(true)
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return freqOptions[row]
}
#objc func freqTap(gestureReconizer: UITapGestureRecognizer) {
freqPicker.isHidden = false
}
}
you don't need to add a picker as a subview. You just need to set it Like an input view (and you already done it). I modified you code. You can just compare and check what was wrong there
class ViewController: UIViewController, UITextFieldDelegate, UIPickerViewDelegate, UIPickerViewDataSource {
#IBOutlet weak var freq: UILabel!
var freqOptions = ["Hz", "kHz", "MHz"]
var freqPicker = UIPickerView()
#IBOutlet weak var freqTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
freqPicker = UIPickerView()
freqPicker.backgroundColor = UIColor.white
freqPicker.delegate = self
freqPicker.dataSource = self
// freqPicker.isHidden = true
let toolBar = UIToolbar()
let cancelItem = UIBarButtonItem(
title: "Cancel",
style: .plain,
target: self,
action: #selector(cancelFreqInput)
)
let middleItem = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneItem = UIBarButtonItem(
title: "Done",
style: .done,
target: self,
action: #selector(confirmFreqInput)
)
toolBar.setItems( [cancelItem, middleItem, doneItem], animated : false )
toolBar.sizeToFit()
// view.addSubview(freqPicker)
let freqTap = UITapGestureRecognizer(target: self, action: #selector(freqTap(gestureReconizer:)))
freq.addGestureRecognizer(freqTap)
freqTextField.inputView = freqPicker
freqTextField.inputAccessoryView = toolBar
freqTextField.isHidden = true
freq.isUserInteractionEnabled = true
freqPicker.reloadComponent(0)
}
#objc func cancelFreqInput() {
freqTextField.resignFirstResponder()
freq.text = "Hz"
freqTextField.isHidden = true
}
#objc func confirmFreqInput() {
freq.text = freqOptions[freqPicker.selectedRow(inComponent: 0)]
self.view.endEditing(true)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return freqOptions.count
}
// func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
// freq.text = freqOptions[row]
// self.view.endEditing(true)
// }
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return freqOptions[row]
}
#objc func freqTap(gestureReconizer: UITapGestureRecognizer) {
freqTextField.becomeFirstResponder()
}
}
I have three TextFields in a Viewcontroller. After clicking the first I want to use UIPickerview to select something. The second TF should open the keyboard and the third one should open UIDatepicker.
import UIKit
class NewCompetitionViewController: UIViewController, UITextViewDelegate,UIPickerViewDataSource, UIPickerViewDelegate{
#IBOutlet weak var programTextField: UITextField!
let program = ["Big Target - 60 Shots",
"Big Target - 30 Shots",
"Small Target - 40 Shots"]
var selectedProgram: String?
let datePicker = UIDatePicker()
#IBOutlet weak var locationTextField: UITextField!
#IBOutlet weak var dateTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
createProgramPicker()
createDatePicker()
}
#IBAction func saveButton(_ sender: UIButton) {
dismiss(animated: true)
}
#IBAction func cancelButton(_ sender: UIButton) {
dismiss(animated: true)
}
// PROGRAM PICKER
func createProgramPicker(){
let programPicker = UIPickerView()
let toolBarPP = UIToolbar()
programPicker.delegate = self
// Customizations
programPicker.backgroundColor = .white
toolBarPP.sizeToFit()
let spaceButtonPP = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneButtonPP = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(dismissKeyboard))
toolBarPP.setItems([spaceButtonPP, doneButtonPP], animated: false)
//toolBarPP.isUserInteractionEnabled = true
programTextField.inputAccessoryView = toolBarPP
programTextField.inputView = programPicker
}
// DISMISS KEYBOARD
#objc func dismissKeyboard(){
self.view.endEditing(true)
}
// DATE PICKER
func createDatePicker(){
datePicker.datePickerMode = .date
datePicker.backgroundColor = .white
let toolbarDP = UIToolbar()
toolbarDP.sizeToFit()
// flexible Space Button and Done button
let spaceButtonDP = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneButtonDP = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(doneClicked))
toolbarDP.setItems([spaceButtonDP, doneButtonDP], animated: false)
//toolbarDP.isUserInteractionEnabled = true
dateTextField.inputAccessoryView = toolbarDP
dateTextField.inputView = datePicker
}
#objc func doneClicked(){
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/YYYY"
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
dateTextField.text = dateFormatter.string(from: datePicker.date)
self.view.endEditing(true)
}
// Returns true after "Done" clicked
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
// Hide the keyboard
textField.resignFirstResponder()
return true
}
private func textFieldDidEndEditing(_ textField: UITextField){
locationTextField.text = textField.text
}
}
extension NewCompetitionViewController: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return program.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return program[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectedProgram = program[row]
programTextField.text = selectedProgram
}
}
I can start the simulation and the UIPickerview works. Also the input on the keyboard at the second textfield. But if I open the datePicker and I click the done-button the display slides up from the bottom to the top with a transparent blue look.
Here are some screenshots:
Main screen
Program selection
Date selection
Bluescreen after clicking done
Sometimes the simplest things prove the hardest to work out! The picker is displayed when users select the user location text field but the selectors are not working. Gone through SO and Apple docs but can't work out why this is.
let locationPicker = UIPickerView()
var locationData = [String]()
override func viewDidLoad() {
super.viewDidLoad()
// Set textfield delegate
userID.delegate = self
userLocation.delegate = self
// Set up picker view for location selection
locationPicker.frame = CGRect(x:0, y: self.view.bounds.height, width: self.view.bounds.width, height: 140)
locationPicker.showsSelectionIndicator = true
let doneButton = UIBarButtonItem(title: "done", style: .plain, target: self, action: #selector(self.closePicker(sender:)))
let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
let cancelButton = UIBarButtonItem(title: "cancel", style: .plain, target: self, action: #selector(self.closePicker(sender:)))
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.blackOpaque
toolBar.isTranslucent = true
toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
userLocation.inputView = locationPicker
userLocation.inputAccessoryView = toolBar
// Load locations into array
let ref: FIRDatabaseReference = FIRDatabase.database().reference().child("venues")
ref.observe(.value, with: { snapshot in
// Pull out the keys to represent locations
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshots {
print("snap key, \(snap.key) and snap value \(snap.value)")
let loc : String = snap.key
self.locationData.append(loc)
}
}
// Now stick the array of locations into the picker view
self.locationPicker.dataSource = self
self.locationPicker.delegate = self
self.locationPicker.reloadAllComponents()
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.endEditing(true)
return false
}
func closePicker(sender: AnyObject) {
print("Close picker")
self.locationPicker.isHidden = true
}
func textFieldDidBeginEditing(_ textField: UITextField) {
if let iText = userID.text, let lText = userLocation.text, !iText.isEmpty, !lText.isEmpty
{
print("We have data")
// loginButton.isUserInteractionEnabled = true
// loginButton.alpha = 1.0
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return locationData.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return locationData[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
userLocation.text = locationData[row]
}
I created a custom pickerview as a keyboard with a done button and everything, but I'm having a bit of trouble figuring out how to load the data immediately from the start, I did it in my datepicker, but now I'm trying to figure out how to do it in a normal picker keyboard that I custom made.
Here is my code:
import UIKit
import CoreData
class ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource, NSFetchedResultsControllerDelegate {
#IBOutlet weak var stateText: UITextField!
#IBOutlet weak var taxNumb: UITextField!
#IBOutlet weak var output: UILabel!
func doneButton() {
let doneToolbar : UIToolbar = UIToolbar(frame: CGRectMake(0, 0, 320, 50))
doneToolbar.barStyle = UIBarStyle.Default
let flexSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
let done : UIBarButtonItem = UIBarButtonItem(title: "Done", style: .Done, target: self, action: ("doneButtonAction"))
var items = [UIBarButtonItem]()
items.append(flexSpace)
items.append(done)
doneToolbar.items = items
doneToolbar.sizeToFit()
self.stateText.inputAccessoryView = doneToolbar
self.taxNumb.inputAccessoryView = doneToolbar
}
func doneButtonAction() {
self.stateText.resignFirstResponder()
self.taxNumb.resignFirstResponder()
}
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let tax : Tax? = nil
var stateArray = [
"AK - Alaska",
"AL - Alabama",
"AR - Arkansas",
"AZ - Arizona",
"CA - California",
]
func statePickerKey() {
let statePickerView = UIPickerView()
statePickerView.dataSource = self
statePickerView.delegate = self
stateText.inputView = statePickerView
}
override func viewDidLoad() {
super.viewDidLoad()
statePickerKey()
doneButton()
}
override func viewDidAppear(animated: Bool) {
statePickerKey()
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return stateArray.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return stateArray[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
return stateText.text = stateArray[row] as String
}
#IBAction func printTapped(sender: AnyObject) {
let entityDescription = NSEntityDescription.entityForName("Tax", inManagedObjectContext: moc)
let taxes = Tax(entity: entityDescription!, insertIntoManagedObjectContext: moc)
taxes.state = stateText.text
if stateText.text == "AK - Alaska" {
taxes.alaska = Double(taxNumb.text!)
output.text = taxes.alaska?.stringValue
} else if stateText.text == "AL - Alabama" {
taxes.alabama = Double(taxNumb.text!)
self.output.text = taxes.alabama?.stringValue
} else if stateText.text == "AR - Arkansas" {
taxes.arkansas = Double(taxNumb.text!)
output.text = taxes.arkansas?.stringValue
} else if stateText.text == "AZ - Arizona" {
taxes.arizona = Double(taxNumb.text!)
output.text = taxes.arizona?.stringValue
} else if stateText.text == "CA - California" {
taxes.california = Double(taxNumb.text!)
output.text = taxes.california?.stringValue
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
you create datepicker, after that set textfield.text = datePickerView.date
I have two UiTextfield which are supposed to show different UiPickerView when clicked on a respective UiTextfield.......
so i used this
if(textField.isFirstResponder() == true)
to find which textfield has been clicked...this does not work
class ViewController: UIViewController, UIPickerViewDataSource , UIPickerViewDelegate {
var pickerData = ["11", "12", "13"]
var pickerDataOthr = ["ada","daad","ada","daad","ada","daad","ada","daad"]
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var textFieldTwo: UITextField!
#IBOutlet weak var tftw: UITextField!
func pickerCode(){
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
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int{
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
var count: Int
if(textField.isFirstResponder() == true)
{
count = pickerData.count
}
else
{
count = pickerDataOthr.count
}
return count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
var stro:String
if(textField.isFirstResponder() == true)
{
stro = pickerData[row]
}
else
{
stro = pickerDataOthr[row]
}
return stro
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if(textField.isFirstResponder() == true)
{
textField.text = pickerData[row]
}
else
{
textFieldTwo.text = pickerDataOthr[row]
}
}
func donePicker(){
if(textField.isFirstResponder() == true)
{
textField.resignFirstResponder()
}
else
{
textFieldTwo.resignFirstResponder()
}
}
func canclePicker(){
if(textField.isFirstResponder() == true)
{
textField.resignFirstResponder()
}
else
{
textFieldTwo.resignFirstResponder()
}
}
}
Adding a tag to every textfield
var tagMaster: Int!
func setUpTag(){
textField.tag = 1
textField.delegate = self
textFieldtwo.tag = 2
textFieldtwo.delegate = self
}
and in the picker helper methods idetify the clicked picker by the picker tags. In place of
textField.isFirstResponder()
i used
textField.tag