How to Load data into textfield when pickerview is launched - ios

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

Related

incorrect array showing in UIPickerView

I have two UIPickerviews that appear on one ViewController. I have tried to follow the following tutorial.
I have followed the suggestion in that I have tagged each of the UITextFields (I have 4 in total). See the the image.
Below is the code for the UIPickerViews.
extension DriverViewController: UIPickerViewDelegate, UIPickerViewDataSource {
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView.tag == 0 {
return tracks.count
} else {
return drivers.count
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView.tag == 0 {
return "\(tracks[row])"
} else {
return "\(drivers[row])"
}
}
The problem I am having is that the tracks array appear on all of the UITextfields.
Below is the code for each of the Arrays and the title of the UIPickerView.
override func viewDidLoad() {
super.viewDidLoad()
tracks = ["Melbourne", "Manama", "Shanghai", "Baku",
"Barcelona", "Monaco", "Montreal","Le Castellet","Spielberg",
"Silverstone","Hockenheim","Budapest","Francorchamps","Monza","Singapore","Sochi","Suzuka","Austin","Interlagos","Abu Dhabi"]
drivers = ["Lewis Hamilton","Antonio Giovinazzi","Kimi Raikkonen","Charles Leclerc","Sebastian Vettel","Romain Grosjean","Kevin Magnussen","Lando Norris",
"Carlos Sainz","Valtteri Bottas","Sergio Perez","Lance Stroll","Pierre Gasly","Max Verstappen","Nico Hulkenberg","Daniel Ricciardo","Alexander Albon","Daniil Kvyat","Robert Kubica","George Russell"]
createTrackPicker()
createDriverPicker()
createToolBar()
// Do any additional setup after loading the view.
}
func createTrackPicker() {
let trackPicker = UIPickerView()
trackPicker.delegate = self
TrackTextField.inputView = trackPicker
}
func createDriverPicker() {
let driverPicker = UIPickerView()
driverPicker.delegate = self
firstTextField.inputView = driverPicker
secondTextField.inputView = driverPicker
thirdTextField.inputView = driverPicker
}
func createToolBar() {
let toolBar = UIToolbar()
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(ViewController.dismissKeyboard))
toolBar.setItems([doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
TrackTextField.inputAccessoryView = toolBar
firstTextField.inputAccessoryView = toolBar
secondTextField.inputAccessoryView = toolBar
thirdTextField.inputAccessoryView = toolBar
}
#objc func dismissKeyboard() {
view.endEditing(true)
}
You forgot the tag.
func createDriverPicker() {
let driverPicker = UIPickerView()
driverPicker.tag = 1 // <—-

pickerView didSelectRow is inputting into the wrong UITextField

I am trying to follow the following solution to having multiple UIPickerViews on the one UIViewController. They suggest that a tag for each of the UITextfield which I have done and able to implement the number of rows, title for row and number of components. However, I have reached a stumbling block when implementing the did select row. When I select the UITextField it highlights another UITextfield. Below is the code I have so far.
class DriverViewController: UIViewController {
var selectedTrack: String?
var firstDriver: String?
var secondDriver: String?
var thirdDriver: String?
let tracks = ["Melbourne", "Manama", "Shanghai", "Baku",
"Barcelona", "Monaco", "Montreal","Le Castellet","Spielberg",
"Silverstone","Hockenheim","Budapest","Francorchamps","Monza","Singapore","Sochi","Suzuka","Austin","Interlagos","Abu Dhabi"]
let drivers = ["Lewis Hamilton","Antonio Giovinazzi","Kimi Raikkonen","Charles Leclerc","Sebastian Vettel","Romain Grosjean","Kevin Magnussen","Lando Norris",
"Carlos Sainz","Valtteri Bottas","Sergio Perez","Lance Stroll","Pierre Gasly","Max Verstappen","Nico Hulkenberg","Daniel Ricciardo","Alexander Albon","Daniil Kvyat","Robert Kubica","George Russell"]
#IBOutlet weak var TrackTextField: UITextField!
#IBOutlet weak var firstTextField: UITextField!
#IBOutlet weak var secondTextField: UITextField!
#IBOutlet weak var thirdTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
createTrackPicker()
createDriverPicker()
createToolBar()
// Do any additional setup after loading the view.
}
func createTrackPicker() {
let trackPicker = UIPickerView()
trackPicker.tag = 0
trackPicker.delegate = self
TrackTextField.inputView = trackPicker
}
func createDriverPicker() {
let driverPicker = UIPickerView()
driverPicker.tag = 1
driverPicker.tag = 2
driverPicker.tag = 3
driverPicker.delegate = self
firstTextField.inputView = driverPicker
secondTextField.inputView = driverPicker
thirdTextField.inputView = driverPicker
}
func createToolBar() {
let toolBar = UIToolbar()
toolBar.sizeToFit()
let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(ViewController.dismissKeyboard))
toolBar.setItems([doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
TrackTextField.inputAccessoryView = toolBar
firstTextField.inputAccessoryView = toolBar
secondTextField.inputAccessoryView = toolBar
thirdTextField.inputAccessoryView = toolBar
}
#objc func dismissKeyboard() {
view.endEditing(true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
extension DriverViewController: UIPickerViewDelegate, UIPickerViewDataSource {
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView.tag == 0 {
return tracks.count
} else {
return drivers.count
}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView.tag == 0 {
return "\(tracks[row])"
} else {
return "\(drivers[row])"
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if pickerView.tag == 0 {
selectedTrack = tracks[row]
TrackTextField.text = selectedTrack
} else if pickerView.tag == 1 {
firstDriver = drivers[row]
firstTextField.text = firstDriver
} else if pickerView.tag == 2 {
secondDriver = drivers[row]
secondTextField.text = secondDriver
} else if pickerView.tag == 3 {
thirdDriver = drivers[row]
thirdTextField.text = thirdDriver
}
}
}
This is how it looks on the screen.
Look at your function:
func createDriverPicker() {
let driverPicker = UIPickerView()
driverPicker.tag = 1
driverPicker.tag = 2
driverPicker.tag = 3
driverPicker.delegate = self
firstTextField.inputView = driverPicker
secondTextField.inputView = driverPicker
thirdTextField.inputView = driverPicker
}
Think about what value the tag property has after this code is run keeping in mind that it can only have one value.
You either need to update the picker view's tag property each time a text field begins editing, or you should abandon the use of the tag and simply check which text field is currently the first responder. See UIPickerView for each text field with different arrays (Swift/Firebase) for an example of how this is done.

UIPickerView for each text field with different arrays (Swift/Firebase)

I am trying to create a form in which each text field has a UIPickerView which the user can use to select the option needed. I need a to use a different array of information for each text field but I can't seem to get it to work and I have been stuck on it for quite a while now.
I have had a method which was possibly working but I couldn't then retrieve the data from the text field for Firebase due to each field having the same name.
Here is my code so far, this is the latest method that I have tried that doesn't work:
import UIKit
import Firebase
import FirebaseDatabase
class CreatePostViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate {
#IBOutlet weak var gameTextField: UITextField!
#IBOutlet weak var activityTextField: UITextField!
#IBOutlet weak var consoleTextField: UITextField!
#IBOutlet weak var skillTextField: UITextField!
#IBOutlet weak var communicationTextField: UITextField!
#IBOutlet weak var lfglfmTextField: UITextField!
#IBOutlet weak var rulesTextView: UITextView!
#IBOutlet weak var descriptionTextView: UITextView!
var games = ["Assassin's Creed Origins", "Battlefield 1", "Call of Duty: Advanced Warfare", "Call of Duty: Black Ops III", "Call of Duty: Ghosts", "Call of Duty: Infinite Warfare", "Call of Duty: Modern Warfare Remastered", "Call of Duty: WWII", "Destiny", "Destiny 2", "Fifa 16", "Fifa 17", "Fifa 18", "Rocket League"]
var console = ["Xbox One", "Xbox 360", "Playstation 4", "Playstation 3"]
var skill = ["Achiever", "Explorer", "Killer", "Socializer"]
var communication = ["Mic", "No Mic"]
var lfglfm = ["LFG", "LFM"]
var itemSelected = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//remove margin / padding from textview
self.rulesTextView.textContainerInset = .zero
self.rulesTextView.contentInset = UIEdgeInsetsMake(0, -5, 0, 0)
// self.descriptionTextView.textContainerInset = .zero
// self.descriptionTextView.contentInset = UIEdgeInsetsMake(0, -5, 0, 0)
//allow tap on screen to remove text field input from screen
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))))
//UIPICKER
let pickerView = UIPickerView()
pickerView.delegate = self
pickerView.dataSource = self
gameTextField.inputView = pickerView
consoleTextField.inputView = pickerView
skillTextField.inputView = pickerView
communicationTextField.inputView = pickerView
lfglfmTextField.inputView = pickerView
updatePicker()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//update pickerView
func updatePicker(){
let pickerView = UIPickerView()
pickerView.reloadAllComponents()
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if gameTextField.isFirstResponder{
return games.count
}else if consoleTextField.isFirstResponder{
return console.count
}else if skillTextField.isFirstResponder{
return skill.count
}else if communicationTextField.isFirstResponder{
return communication.count
}else if lfglfmTextField.isFirstResponder{
return lfglfm.count
}
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
if gameTextField.isFirstResponder{
return games[row]
}else if consoleTextField.isFirstResponder{
return console[row]
}else if skillTextField.isFirstResponder{
return skill[row]
}else if communicationTextField.isFirstResponder{
return communication[row]
}else if lfglfmTextField.isFirstResponder{
return lfglfm[row]
}
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if gameTextField.isFirstResponder{
let itemselected = games[row]
gameTextField.text = itemselected
}else if consoleTextField.isFirstResponder{
let itemselected = console[row]
consoleTextField.text = itemselected
}else if skillTextField.isFirstResponder{
let itemselected = skill[row]
skillTextField.text = itemselected
}else if communicationTextField.isFirstResponder{
let itemselected = communication[row]
communicationTextField.text = itemselected
}else if lfglfmTextField.isFirstResponder{
let itemselected = lfglfm[row]
lfglfmTextField.text = itemselected
}
}
#IBAction func createPostTapped(_ sender: UIButton) {
if let uid = Auth.auth().currentUser?.uid {
Database.database().reference().child("usernames").child(uid).observeSingleEvent(of: .value, with: {
(snapshot) in
if let userDictionary = snapshot.value as? [String: AnyObject] {
for user in userDictionary {
if let username = user.value as? String {
if let game = self.gameTextField.text {
if let activity = self.activityTextField.text {
if let console = self.consoleTextField.text {
if let skill = self.skillTextField.text {
if let communication = self.communicationTextField.text {
if let lfglfm = self.lfglfmTextField.text {
if let description = self.descriptionTextView.text {
let postObject: Dictionary<String, Any> = [
"uid" : uid,
"username" : username,
"game" : game,
"activity" : activity,
"console" : console,
"skill" : skill,
"communication" : communication,
"lfglfm" : lfglfm,
"description" : description
]
Database.database().reference().child("posts").childByAutoId().setValue(postObject)
let alert = UIAlertController(title: "Success!", message: "Your post was added successfully.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
//code will run when ok button is pressed
let vc = self.storyboard?.instantiateViewController(withIdentifier: "LoggedInVC")
self.present(vc!, animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
}
}
}
}
}
}
}
}
}
})
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
If anyone knows of a successful method which I can implement please feel free contribute it would be much appreciated.
Thank you.
Your code is almost right. I would just store a class attribute with the UIPickerView so you can reload the components upon textField editing status change. For that purpose, you have also to set the textField delegates.
Here a working example with the adjustments I just commented:
import UIKit
class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate {
#IBOutlet weak var gameTextField: UITextField!
#IBOutlet weak var activityTextField: UITextField!
#IBOutlet weak var consoleTextField: UITextField!
#IBOutlet weak var skillTextField: UITextField!
#IBOutlet weak var communicationTextField: UITextField!
#IBOutlet weak var lfglfmTextField: UITextField!
var games = ["Assassin's Creed Origins", "Battlefield 1", "Call of Duty: Advanced Warfare", "Call of Duty: Black Ops III", "Call of Duty: Ghosts", "Call of Duty: Infinite Warfare", "Call of Duty: Modern Warfare Remastered", "Call of Duty: WWII", "Destiny", "Destiny 2", "Fifa 16", "Fifa 17", "Fifa 18", "Rocket League"]
var console = ["Xbox One", "Xbox 360", "Playstation 4", "Playstation 3"]
var skill = ["Achiever", "Explorer", "Killer", "Socializer"]
var communication = ["Mic", "No Mic"]
var lfglfm = ["LFG", "LFM"]
var itemSelected = ""
weak var pickerView: UIPickerView?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//remove margin / padding from textview
// self.descriptionTextView.textContainerInset = .zero
// self.descriptionTextView.contentInset = UIEdgeInsetsMake(0, -5, 0, 0)
//allow tap on screen to remove text field input from screen
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing(_:))))
//UIPICKER
let pickerView = UIPickerView()
pickerView.delegate = self
pickerView.dataSource = self
gameTextField.delegate = self
consoleTextField.delegate = self
skillTextField.delegate = self
communicationTextField.delegate = self
lfglfmTextField.delegate = self
gameTextField.inputView = pickerView
consoleTextField.inputView = pickerView
skillTextField.inputView = pickerView
communicationTextField.inputView = pickerView
lfglfmTextField.inputView = pickerView
//It is important that goes after de inputView assignation
self.pickerView = pickerView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldDidBeginEditing(_ textField: UITextField) {
self.pickerView?.reloadAllComponents()
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if gameTextField.isFirstResponder{
return games.count
}else if consoleTextField.isFirstResponder{
return console.count
}else if skillTextField.isFirstResponder{
return skill.count
}else if communicationTextField.isFirstResponder{
return communication.count
}else if lfglfmTextField.isFirstResponder{
return lfglfm.count
}
return 0
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if gameTextField.isFirstResponder{
return games[row]
}else if consoleTextField.isFirstResponder{
return console[row]
}else if skillTextField.isFirstResponder{
return skill[row]
}else if communicationTextField.isFirstResponder{
return communication[row]
}else if lfglfmTextField.isFirstResponder{
return lfglfm[row]
}
return nil
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if gameTextField.isFirstResponder{
let itemselected = games[row]
gameTextField.text = itemselected
}else if consoleTextField.isFirstResponder{
let itemselected = console[row]
consoleTextField.text = itemselected
}else if skillTextField.isFirstResponder{
let itemselected = skill[row]
skillTextField.text = itemselected
}else if communicationTextField.isFirstResponder{
let itemselected = communication[row]
communicationTextField.text = itemselected
}else if lfglfmTextField.isFirstResponder{
let itemselected = lfglfm[row]
lfglfmTextField.text = itemselected
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
EDITED:
You don't need the updatePicker method. It does nothing indeed.
I've deleted the createPostTapped method for the purpose of this simple example.
you can assign your selected value to particular text field by using textField delegate methods which is textFieldDidBeginediting which is called when textField did started begin editing
like
take one variable
var textFieldSelected = UITextField()
and then in
func textFieldDidBeginEditing(_ textField: UITextField) {
textFieldSelected = textField
}
by doing this you will get you selected textField
and when you done choosing from picker
func doneSelection(){
if textFieldSelected == yourTextField(in which you want to enter your data)
{
yourTextField.text = data you want to enter from picker
}
}

Multiple UIPickerView in one ViewController

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

Save uipickerview color in core data

I know what I want, but I'm just struggling to get it the right way. I'm trying to implement a small app, which let the user add a category by providing a category name, description and then select colour from the uipickerview. I've successfully saved the name, description in the core data. I'm just struggling in how to get the selected colour string and save it in the core data. Any help will be appreciated. This is what I've so far as code:
import UIKit
import CoreData
class NewCategory: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
let categoryColor = ["Red","Yellow","Black","White", "Green", "Blue"]
// MARK: - Properties
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
// MARK: Outlets
#IBOutlet weak var name: UITextField!
#IBOutlet weak var descriptionField: UITextView!
#IBOutlet weak var pickerView: UIPickerView!
#IBOutlet weak var colorLabel: UILabel!
// MARK: Actions
#IBAction func saveBtn(sender: AnyObject) {
if name.text == "" || name.text.isEmpty || name.text.isEmpty{
var alert = UIAlertController(title: "WARNING !!!", message: "Couldn't add category. Fill all fields.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
} else {
createCategory() }
}
// MARK: View settings
override func viewDidLoad() {
super.viewDidLoad()
self.pickerView.dataSource = self
self.pickerView.delegate = self
}
// Custom functions
func createCategory() {
let entity = NSEntityDescription.entityForName("Category", inManagedObjectContext: context!)
let category = Category(entity: entity!, insertIntoManagedObjectContext: context)
category.name = name.text
category.descript = descriptionField.text
category.color = colorLabel
println(category.name)
context?.save(nil)
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return categoryColor.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
return categoryColor[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if (row == 0) {
colorLabel.backgroundColor = UIColor.redColor()
}
else if(row == 1) {
colorLabel.backgroundColor = UIColor.yellowColor()
}
else if(row == 2) {
colorLabel.backgroundColor = UIColor.blackColor()
}
else if(row == 3) {
colorLabel.backgroundColor = UIColor.whiteColor()
}
else if(row == 4) {
colorLabel.backgroundColor = UIColor.greenColor()
}
else {
colorLabel.backgroundColor = UIColor.blueColor()
}
}
}
You can get the color name this way:
let index = pickerView.selectedRowInComponent(0)
let color = categoryColor[index]
For example, you could use it in your function like this:
func createCategory() {
let entity = NSEntityDescription.entityForName("Category", inManagedObjectContext: context!)
let category = Category(entity: entity!, insertIntoManagedObjectContext: context)
category.name = name.text
category.descript = descriptionField.text
let index = pickerView.selectedRowInComponent(0)
let color = categoryColor[index]
category.color = color // (assuming color is a String)
println(category.name)
context?.save(nil)
}
In didSelectRow get the value from categoryColor
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let colorString = categoryColor[row] as! String
// Save the colorString into Core data
}

Resources