Quantcast
Channel: Active questions tagged uipickerview - Stack Overflow
Viewing all 593 articles
Browse latest View live

How to enabled button after user select value from UIPickerView?

$
0
0

I have created a new contact form I have 3 first name, Lastname, email country and create button, I enable the create button after firstname,Lastname and email when they are not empty. the county text field is populated after selecting from county PcikerView I test !txtfCountry.text!.isEmpty on my editingChanged function but is not working.

self.txtfCountry.addTarget(self, action: #selector(editingChanged), for: .editingChanged) @IBOutlet var countryPicker : UIPickerView!    @objc func editingChanged(_ textField: UITextField) {        if !txtfFirstname.text!.isEmpty  && !txtfLastname.text!.isEmpty && !txtfEmail.text!.isEmpty  &&  !txtfCountry.text!.isEmpty{            btnNext.isEnabled = true            btnNext.setTitleColor(UIColor.white, for: .normal)        }else{            btnNext.isEnabled = false        }    }

Change the color of the lines in UIPickerView with Swift

$
0
0

Basically I just want to change the color of the seperator lines:

enter image description here

I think for obj-c there is an answer here: link. But I have difficulties to translate it in Swift. How to do that?

Determining which UIPicker's toolbar button sent a message

$
0
0

I am trying to use multiple UIPickers on a page. I think I've configured almost everything. When I use a UIPicker I add in a a tool bar with a "Cancel" and a "Done" Button.

The toolbars are built using the same function, so it calls the same action when a user taps "Done". A pseudo example flow below.

 let pickerData: [String] = ["1", "2", "3", "4"] var picker = UIPickerView() let pickerData2: [String] = ["A", "B", "C", "D"] var picker2 = UIPickerView() @IBOutlet weak var textField: UITextField! @IBOutlet weak var textField2: UITextField!override func viewDidLoad() {  super.viewDidLoad()  // set up pickers  setPickerView()}    // set the pickerviewfunc setPickerView(){    picker.dataSource = self    picker.delegate = self    textField.inputView = picker    textField.inputAccessoryView = initToolBar()    // second picker    picker2.dataSource = self    picker2.delegate = self    textField2.inputView = picker    textField2.inputAccessoryView = initToolBar()}// build the toolbar for uipicker, so a user can select a valuefunc initToolBar() -> UIToolbar {    let toolBar = UIToolbar()    toolBar.barStyle = UIBarStyle.default    toolBar.isTranslucent = true    toolBar.tintColor = UIColor(red:14.0/255, green:122.0/255, blue:254.0/255, alpha: 1)    toolBar.sizeToFit()    // TODO need to update actions for all buttons    let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.plain, target: self, action: nil)    let doneButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(pickerDoneAction))    let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)    toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)    toolBar.isUserInteractionEnabled = true    return toolBar}func pickerDoneAction(sender: UIBarButtonItem){     /*Here I'm just updating the same textfield when the done button is       is pressed, I'm not sure how I can get the instance of the picker into this method*/     let indexPath = picker.selectedRow(inComponent: 0)     textfield.text = data[indexPath]}// delegatesfunc numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 }func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {  if pickerView == picker {    return pickerData.count    } else return pickerData2.count}func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {  if pickerView == picker {    return pickerData[row]  } else return pickerData2[row]}func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {  if pickerView == picker {    textField.text = pickerData[row]  } else textField2.text = pickerData2[row]}

Is there a way to determine which UIPicker was being used when the done button was clicked, so I could use that instance in my pickerDoneAction method and then change the corresponding textfield's value? I tried checking if the textfield was firstResponder and even tried to check the UIPicker itself, but it didn't seem possible. Do I need to change my approach and if so how?

UpdateI've added in my existing UIPicikerView delegate methods.

Just to clarify, I want the value of the UIPicker to be assigned to the correct textfield when a user presses "Done", therefore if a user wants to select the very first row from a UIPicker, it gets inserted.

Saving a value outside of a .observeSingleEvent [duplicate]

$
0
0

I am learning Swift/Firebase as I try to make a app, but the last two days have been tough as I constantly have trouble accessing values outside of brackets.

I am trying to configure a UIPickerView and I want my numberOfRowsInComponent to equal childrenCount of a snapshot. I can get the value of the childrenCount inside of the snapshot no problem, but no matter what I try I can't access it outside of the snapshot, and therefore can't set it as my number of rows. Here is what I tried last:

//declare variable under classvar activeDealCount: Int = 69
///set activeDealCount to correct number///set numberOfRowsInComponent to activeDealCount    @available(iOS 2.0, *)     public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {        ref.child("users").child(userID).child("deals").child("log2").child("Active Deals Array").observeSingleEvent(of: .value, with: { snapshot in            let value = snapshot.childrenCount as UInt            let value2 = Int(value)            self.activeDealCount = value2            print(self.activeDealCount)            //it prints the correct activeDealCount (current value: 5)        })            print("active deal count: "+String(activeDealCount))            return activeDealCount        //it prints and returns the incorrect activeDealCount (69)    }

How do I make my number of rows the new value (5), instead of 69?

Been trying for way too long so I joined stackoverflow, thanks.

UIPIckerViews working together in one UIView

$
0
0

looked at the other similar questions but have not found the answers there. Sorted out some of the issues I had but still have the issue where the data from the first pickerView determines what selections there are in the second pickerView (this part of app is a units convertor).

I understand what is going wrong but cannot see how to fix the problem. Through print statements I can see that when I change the first pickerView, the value which holds the number of rows in the second pickerView changes. But the second pickerView titles do not change so that when I go to an item that is higher than index number in the new array, the app crashes. This is confirmed by the error Index out of range.

I have included code and a snapshot of what the pickerViews look like (no formatting or making it pretty - like to get functionality first).

Thanks for any help.

enter image description here

import UIKit

import Foundation

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

var conversionTypes = ["length", "mass", "area", "volume", "rate", "temp", "pressure"]var conversionItems = [["metres", "feet", "yard", "inch", "cm"], ["kg", "lbs", "tonne", "ounces"], ["ft2", "m2", "in2"], ["US Gall", "UK Gall", "Bbls", "ft3", "m3"], ["bbl/min", "scf/min", "scf/hr"], ["degC", "degF", "Kelvin"], ["bar", "psi"]]var littlePickerType = 0var wheelOne = 0var wheelTwo = 0@IBOutlet weak var numberToConvert: UITextField!@IBOutlet weak var answerLabel: UILabel!@IBOutlet weak var littlePicker: UIPickerView!@IBOutlet weak var bigPicker: UIPickerView!override func viewDidLoad() {    super.viewDidLoad()    // Do any additional setup after loading the view.    littlePicker.delegate = self    littlePicker.dataSource = self    bigPicker.delegate = self    bigPicker.dataSource = self    let tap = UITapGestureRecognizer(target: self.view, action: #selector(UIView.endEditing))    view.addGestureRecognizer(tap)}func numberOfComponents(in pickerView: UIPickerView) -> Int {    if pickerView == littlePicker {        return 1    } else if pickerView == bigPicker {        return 2    }    return 1}func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {    if pickerView == littlePicker {        return conversionTypes.count    } else if pickerView == bigPicker {        return conversionItems[littlePickerType].count    }    return 1}func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {    if pickerView == littlePicker {        return conversionTypes[row]    } else if pickerView == bigPicker {        return conversionItems[littlePickerType][row]    }    return ""}func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {    if pickerView == littlePicker {        littlePickerType = row    } else if pickerView == bigPicker {        if component == 0 {            wheelOne = row        } else if component == 1 {            wheelTwo = row        }    }    print ("Conversion Type \(littlePickerType) WheelOne \(wheelOne) WheelTwo \(wheelTwo) count \(conversionItems[littlePickerType].count)")}

}

Correct work with UIPickerVIew with two numbers components

$
0
0

I want to choose in the first component number five (for example) and want the second component are automatically displayed digit +1 from the selected digit in the first component (i.e. six), and to a second component retired numbers to five (or another if I choose).

How can I do this correctly?

Now my code is empty:

var numbers: [Int] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]func numberOfComponents(in pickerView: UIPickerView) -> Int {    return 2}func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {    if component == 0 {        return numbers.count    } else {        return numbers.count    }}func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {    if component == 0 {        return "\(numbers[row])"    } else {        return "\(numbers[row])"    }}func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {}

enter image description here

Swapping through UITextFields constraint issue

$
0
0

I have an EditProfileViewController, with a tableview and textfields. In one of the textfields I have a pickerView as inputView and a toolBar in the inputAccessoryView. When the view loads and I select the firstName textfield, and return and move on to the lastName textfield, I get a constraint warning.

[LayoutConstraints] Unable to simultaneously satisfy constraints.Probably at least one of the constraints in the following list is one you don't want. Try this:     (1) look at each constraint and try to figure out which you don't expect;     (2) find the code that added the unwanted constraint or constraints and fix it. ("<NSLayoutConstraint:0x2809a4640 'assistantHeight' TUISystemInputAssistantView:0x1113b11a0.height == 45   (active)>","<NSLayoutConstraint:0x2809a0320 'assistantView.bottom' TUISystemInputAssistantView:0x1113b11a0.bottom == _UIKBCompatInputView:0x11a437e80.top   (active)>","<NSLayoutConstraint:0x2809a05a0 'assistantView.top' V:|-(0)-[TUISystemInputAssistantView:0x1113b11a0]   (active, names: '|':UIInputSetHostView:0x11d06ce50 )>","<NSLayoutConstraint:0x280943840 'inputView.top' V:|-(0)-[_UIKBCompatInputView:0x11a437e80]   (active, names: '|':UIInputSetHostView:0x11d06ce50 )>")Will attempt to recover by breaking constraint <NSLayoutConstraint:0x2809a0320 'assistantView.bottom' TUISystemInputAssistantView:0x1113b11a0.bottom == _UIKBCompatInputView:0x11a437e80.top   (active)>

When I switch between two default textfields this happens, and I don't understand why. I did some research and from what I can see this is a bug with iOS 13, since on another device with iOS 10, this does not happened.

The workaround to remove this constraint issue is to set the autoCorrectionType = false. But I would like to have this enabled. I think this happens because I have a pickerView in the inputView of the countryTextfield, but I don't know how to solve this.

How to make such kind of UIPickerView? [closed]

$
0
0

How can I do PickerView as in the picture? Thanksenter image description here


How to use Multiple UIPickerViews in same View controller using UITextFields

$
0
0

I am trying to have multiple picker views in one single view in Objective-C. So far I have created 3 different textfields and I want three of them to have different picker views if I click on them. so let us say if click on textfield #1 it opens the array #1 and textfields #2 the second and textfields # third one. If i click the first and second text fields related picker view displaying but if i click the third one picker view is not showing.

-(void)viewDidLoad{

isBloodGroupFieldSelected = YES;

isGenderGroupFieldSelected = YES;

// Do any additional setup after loading the view.

bloodGroup = [[UITextField alloc]initWithFrame:CGRectMake(10, 100, self.view.frame.size.width-10,30)];

[self.view addSubview:bloodGroup];

txtField1 = [[UITextField alloc]initWithFrame:CGRectMake(10, 160, self.view.frame.size.width-10,30)];

txtField1.delegate = self;

[self.view addSubview:txtField1];

txtField2 = [[UITextField alloc]initWithFrame:CGRectMake(10, 210, self.view.frame.size.width-10,30)];

txtField2.delegate = self;

[self.view addSubview:txtField2];

dataArray = [[NSMutableArray alloc]initWithObjects:@"A+",@"A-",@"B+",@"B-",@"O+",@"O-", nil];

genderArray = [[NSMutableArray alloc]initWithObjects:@"Male",@"Female", nil];

ageArray = [[NSMutableArray alloc]initWithObjects:@"Age1",@"Age2", nil];

myPickerView = [[UIPickerView alloc] init];

[myPickerView setDataSource: self];

[myPickerView setDelegate: self];

myPickerView.showsSelectionIndicator = YES;

UIBarButtonItem *doneButton = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDonetarget:self action:@selector(done:)];

UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height-myPickerView.frame.size.height-50, 320, 50)];

[toolBar setBarStyle:UIBarStyleBlackOpaque];

NSArray *toolbarItems = [NSArray arrayWithObjects:doneButton, nil];

[toolBar setItems:toolbarItems];

bloodGroup.inputView = myPickerView;

bloodGroup.inputAccessoryView = toolBar;

// txtField1

txtField1.inputView = myPickerView;

txtField1.inputAccessoryView = toolBar;

txtField2.inputView = myPickerView;

txtField2.inputAccessoryView = toolBar;

}

-(void)done:(id)sender{

[bloodGroup resignFirstResponder];

[txtField1 resignFirstResponder];

[txtField2 resignFirstResponder];

}

pragma mark - UIPickerViewDataSource

// #3-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {

if (isBloodGroupFieldSelected) {

return 1;

}

else if(!isBloodGroupFieldSelected){

return 1;

}

else if(!isGenderGroupFieldSelected){

return 1;

}

return 0;

}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {

if (isBloodGroupFieldSelected) {

return [dataArray count];

}

else if(!isBloodGroupFieldSelected)

{

return [genderArray count];

}

else if(!isGenderGroupFieldSelected)

{

return [ageArray count];

}

return 0;

}

pragma mark - UIPickerViewDelegate

// #5-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {

if (isBloodGroupFieldSelected) {

return dataArray[row];

}

else if(!isBloodGroupFieldSelected)

{

return genderArray[row];

}

else if(!isGenderGroupFieldSelected)

{

return ageArray[row];

}

return 0;

}

// #6-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

if (isBloodGroupFieldSelected) {

bloodGroup.text = dataArray[row];

}

else if(!isBloodGroupFieldSelected)

{

txtField1.text = genderArray[row];

}

else if(!isGenderGroupFieldSelected)

{

txtField2.text= ageArray[row];

}

}

  • (void)textFieldDidBeginEditing:(UITextField *)textField {

if (textField == bloodGroup) {

isBloodGroupFieldSelected = YES;

}

else if (textField == txtField1){

isBloodGroupFieldSelected = NO;

isGenderGroupFieldSelected = YES;

}

else if (textField == txtField2){

isGenderGroupFieldSelected = NO;

isBloodGroupFieldSelected = NO;

}

[myPickerView reloadAllComponents];

}

UIPickerView with multiple components crashes app

$
0
0

I have a UIPickerView with 2 components. 1st component is for districts and 2nd components is for cities. When I'm spinning both at once I'm getting an Index out of range and app crashes. I'm loading the data to a dictionary at viewDidLoad(). Each district has multiple cities.

Implementation

func numberOfComponents(in pickerView: UIPickerView) -> Int {    return PickerViewComponents.allCases.count}func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {    let componentName = PickerViewComponents.allCases[component]    switch componentName {    case .district:        return districts.count    case .cities:        let index = pickerView.selectedRow(inComponent: PickerViewComponents.district.rawValue)        let district = districts[index]        return districtsDict[district]!.count    }}func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {    let componentName = PickerViewComponents.allCases[component]    switch componentName {    case .district:        return districts[row]    case .cities:        let index = pickerView.selectedRow(inComponent: PickerViewComponents.district.rawValue)        let district = districts[index]        return districtsDict[district]?[row]    }}func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {    let componentName = PickerViewComponents.allCases[component]    if componentName == .district {        let cities = PickerViewComponents.cities.rawValue        pickerView.reloadComponent(cities)        pickerView.selectRow(0, inComponent: cities, animated: true)    } else {        let index = pickerView.selectedRow(inComponent: PickerViewComponents.district.rawValue)        let district = districts[index]        self.districtsTxtField.text = districtsDict[district]![row]    }}

Update

App crashes at titleForRow method return districtsDict[district]?[row]

This crashes app when spinning the 1st component and while it's spinning I can't spin the second one at the same. Of course this is not a requirement. But need to prevent the app crashes when doing this? Is there a way to fix this?

Making Horizontal UIPickerView

$
0
0

I am trying to make a Horizontal UIPickerView. But i have som issues with the width. As you can se in the top of the image aboveenter image description here

I want the width of the PickerView to be = view.frame.size.width, but for some reason it keeps very small. In my code i have:

let cityPicker = UIPickerView()var rotationAngle: CGFloat!let width:CGFloat = 100let height:CGFloat = 100override func viewDidLoad() {        super.viewDidLoad()cityPicker.delegate = self        cityPicker.dataSource = self        cityPicker.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 50)        self.view.addSubview(cityPicker)        rotationAngle = -90 * (.pi/180)        cityPicker.transform = CGAffineTransform(rotationAngle: rotationAngle)        }  func numberOfComponents(in pickerView: UIPickerView) -> Int {        return 1    }    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {        return byer.count    }     func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {        return 100    }    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {        return 100    }    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {        let view = UIView()        view.frame = CGRect(x: 0, y: 0, width: width, height: height)        let label = UILabel()        label.frame = CGRect(x: 0, y: 0, width: width, height: height)        label.textAlignment = .center        label.font = UIFont (name: "Baskerville-Bold", size: 30)        label.text = byer[row]        view.addSubview(label)        view.transform = CGAffineTransform(rotationAngle: 90 * (.pi/180))        return view    }

Can anyone see what i am doing wrong?

Getting a picker to always show the first element of my array when user select a text field in Xcode

$
0
0

I am building an app that asks the user to select a number that represents scoring from 0 to 6. I give the user the seven options via a picker view. This actions need to be repeated several times until the user has accumulated enough points.

My issue is that, after the initial pick which properly loads on first choice of my array ("0"), the wheel then displays the previous choice made by the user ("3" if choice was "3", "4" if it was "4", etc..) instead of "0" again.

There should be a simple method to call the picker to repeatedly display the first element of the array of data but I can't find it. As you can see I am new to this... Thank you for the help.

Dynamic PickerView with multiple components: Index out of range

$
0
0

I have a PickerView with 3 components based on this code. The two picker to the right change their content based on the previous selection to the left. Unfortunately the app crashes when I change a parent picker to another one with less rows than the previews one: 🛑 Fatal Error: Index out of range.

GIF of the current state and crash

I tried to return the child picker to their first position after selecting another parent picker, but it didn't worked out. (Please see under didSelectRow

Do you have another idea?

func numberOfComponents(in pickerView: UIPickerView) -> Int {    return 3}func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {    if component == 0 {        return countries.count    } else if component == 1 {        let selectedCountry = pickerView.selectedRow(inComponent: 0)        return countries[selectedCountry].cities.count    } else {        let selectedCountry = pickerView.selectedRow(inComponent: 0)        let selectedCity = pickerView.selectedRow(inComponent: 1)        return countries[selectedCountry].cities[selectedCity].posts.count    }}func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {    if component == 0 {        return countries[row].name    } else if component == 1{        let selectedCountry = pickerView.selectedRow(inComponent: 0)        return countries[selectedCountry].cities[row].name    } else {        let selectedCountry = pickerView.selectedRow(inComponent: 0)        let selectedCity = pickerView.selectedRow(inComponent: 1)        return countries[selectedCountry].cities[selectedCity].posts[row]    }}func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {    pickerView.reloadAllComponents()    if component == 0 {        pickerView.selectRow(0, inComponent: 1, animated: true)        pickerView.selectRow(0, inComponent: 2, animated: true)    } else if component == 1 {        pickerView.selectRow(0, inComponent: 2, animated: true)    }}

Error Message

UIPickerView height constraint animation jumps

$
0
0

I'm animating the height constraint of an UIPickerView.The View jumps to a small height still showing 1 row and then animates till height 0.

UIView.animate(withDuration: 0.5, animations: {        self.timePickerHeightConstraint.constant =    self.pickerIsClosed ? 216 : 0        self.view.layoutIfNeeded()    }) { compilation in        self.pickerIsClosed = !self.pickerIsClosed    }

Any suggestions? Thanka

Picker Text color in DarkMode

$
0
0

How do set the text in a Picker control to a light color for iOS13 darkmode

To support DARKMODE on IOS13 you need to set the text color to a colour that the system can change. But on the inspector, there is no ability to set the Picker text to any color.

There must be a simple way to do this but I cannot find it. Using Attributed text is NOT the solution.


multiple pickerview didSelectRow error in Swift

$
0
0

I have 2 pickerviews, 1 pickerview is to select a crypto-currency from an Array and the other pickerview is used to select a currency from an array. The problem I am having is when I run the app on simulator and select the cryptocurreny in cryptoPicker the app it also selects the same array value from currencyPicker and vice a versa. I don't want the array value of 0 to be pulled from both arrays unless it is selected by the user.

@IBOutlet weak var cryptoCurrentRate: UILabel!@IBOutlet weak var currencyLabel: UILabel!@IBOutlet weak var currencyPicker: UIPickerView!@IBOutlet weak var cryptoPicker: UIPickerView!@IBOutlet weak var cryptoLabel: UILabel!var coinManager = CoinManager()override func viewDidLoad() {    super.viewDidLoad()    // Do any additional setup after loading the view.    coinManager.delegate = self    currencyPicker.dataSource = self    currencyPicker.delegate = self    cryptoPicker.dataSource = self    cryptoPicker.delegate = self   }

}

func numberOfComponents(in pickerView: UIPickerView) -> Int {       return 1   }    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {        if pickerView == currencyPicker {        return coinManager.currencyArray.count        }        if pickerView == cryptoPicker {        return coinManager.cryptoArray.count    }        return 0    }    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {        if pickerView == currencyPicker {        return coinManager.currencyArray[row]        }        if pickerView == cryptoPicker {        return coinManager.cryptoArray[row]    }        return ""    }    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {        let selectedCurrency = coinManager.currencyArray[row]        let selectedCrypto = coinManager.cryptoArray[row]        coinManager.fetchCryptoCoin(assetIdBase: selectedCrypto, assetIdQuote: selectedCurrency)    }

}

How to change picker inputView when click different textField?

$
0
0

I have some textField and set a picker be their inputView. It works fine when I tap a textField, then tap another view to close the picker. The issue is when I tap a textField, then tap another textField. The picker change the view but it seems the data count were wrong. The message shows "Thread 1: Fatal error: Index out of range". Now I use 4 UIPickerView be a workaround. May I have some way to use only one UIPickerView be multiple textfield's inputView with different datasource? I think the way is close the inputView before another textField been tapped. Please help. Thank you.

below is the code

class NotificationSearchCustomerViewController: UIViewController, UIScrollViewDelegate, UITextFieldDelegate{let meals = ["a","b","c",""]let citys = ["d","e","f","g","h","i","j","k"]let years = ["1","2","3","4","5"]@IBOutlet weak var birthdayTextField: UITextField!@IBOutlet weak var cityTextField: UITextField!@IBOutlet weak var paymonthTextField: UITextField!@IBOutlet weak var insurancePeriodTextField: UITextField!override func viewDidLoad() {    super.viewDidLoad()    setTextFieldInputView()    birthdayTextField.delegate = self    cityTextField.delegate = self    paymonthTextField.delegate = self    let tap = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard))    self.view.addGestureRecognizer(tap)}@objc func hideKeyboard(){    self.view.endEditing(false)}func setTextFieldInputView(){    let myPickerView1 = UIPickerView()    let myPickerView2 = UIPickerView()    let myPickerView3 = UIPickerView()    let myPickerView4 = UIPickerView()    myPickerView1.delegate = self    myPickerView1.dataSource = self    myPickerView2.delegate = self    myPickerView2.dataSource = self    myPickerView3.delegate = self    myPickerView3.dataSource = self    myPickerView4.delegate = self    myPickerView4.dataSource = self    birthdayTextField.inputView = myPickerView1    cityTextField.inputView = myPickerView2    paymonthTextField.inputView = myPickerView3    insurancePeriodTextField.inputView = myPickerView4}//if use four pickerView, this func can be delete. func textFieldDidBeginEditing(_ textField: UITextField) {    textField.inputView?.reloadInputViews()    if textField == birthdayTextField{        birthdayTextField.becomeFirstResponder()        for i in 0 ..< months.count{            if  months[i] == textField.text{                let picker = birthdayTextField.inputView as? UIPickerView                picker?.selectRow(i, inComponent: 0, animated: false)                break            }        }    }else if textField == cityTextField{        cityTextField.becomeFirstResponder()        for i in 0 ..< citys.count{            if  citys[i] == textField.text{                let picker = textField.inputView as? UIPickerView                picker?.selectRow(i, inComponent: 0, animated: false)                break            }        }    }else if textField == paymonthTextField{        paymonthTextField.becomeFirstResponder()        for i in 0 ..< months.count{            if  months[i] == textField.text{                let picker = paymonthTextField.inputView as? UIPickerView                picker?.selectRow(i, inComponent: 0, animated: false)                break            }        }    }}func textFieldDidEndEditing(_ textField: UITextField){    self.view.endEditing(true)}

}

extension NotificationSearchCustomerViewController: UIPickerViewDelegate, UIPickerViewDataSource{func numberOfComponents(in pickerView: UIPickerView) -> Int {    return 1}func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {    if(birthdayTextField.isFirstResponder || paymonthTextField.isFirstResponder){        return meals.count    }else if(cityTextField.isFirstResponder){        return drinks.count    }else if(insurancePeriodTextField.isFirstResponder){        return years.count    }    return 0}func pickerView(_ pickerView: UIPickerView,  titleForRow row: Int,  forComponent component: Int) -> String? {    if(birthdayTextField.isFirstResponder || paymonthTextField.isFirstResponder){        return meals[row]    }else if(cityTextField.isFirstResponder){        return drinks[row]    }else if(insurancePeriodTextField.isFirstResponder){        return years[row]    }    return ""}func pickerView(_ pickerView: UIPickerView,  didSelectRow row: Int, inComponent component: Int) {    if(birthdayTextField.isFirstResponder){        birthdayTextField.text = meals[row]    }else if(cityTextField.isFirstResponder){        cityTextField.text = drinks[row]    }else if(paymonthTextField.isFirstResponder){        paymonthTextField.text = meals[row]    }else if(insurancePeriodTextField.isFirstResponder){        insurancePeriodTextField.text = years[row]    }    self.view.endEditing(true)}

}

what is the best way to populate a picker view with JSON data in swift?

$
0
0

i am building a COVID-19 app tracker on IOS.

In order to display the data by country, I have built a pickerView that will contain all the country names.

thanks to an HTTP cal, I have managed to get the JSON data i.e the name of each country. ideally I wish to append each value to an array that in turn will populate the pickerView.

Is that possible ? If yes, how would I do that ?

I am also open to other ways to do it. Here is my code :

 @IBOutlet weak var confirmedCasesLabel: UILabel! @IBOutlet weak var deathsLabel: UILabel! @IBOutlet weak var recoveriesLabel: UILabel! //MARK: - Relevant variables private let covidUrl: String = "https://corona-api.com/countries" var countryArray: [String] = [String]() override func viewDidLoad() {     super.viewDidLoad()     // Do any additional setup after loading the view.     countryPickerView.delegate = self     countryPickerView.dataSource = self     //     httpCall() } /* // 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. } */ //MARK: - Functions that handles picker view delegates and data source func numberOfComponents(in pickerView: UIPickerView) -> Int {        return 1    } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {     return countryArray.count    } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {     return countryArray[row] } //MARK: - HTTP CALL - GET COUNTRY DATA func httpCall() {     request(covidUrl, method: .get).responseJSON { (response) in         if response.result.isSuccess {             //test just print some data             let dataJSON: JSON = JSON(response.result.value)             //print(dataJSON)             //on va identifier chaque pays + l'ajouter au tableau des pays//                let countryNameJSON = dataJSON["data"][99]["name"]//                print(countryNameJSON)             for country in 0...99 {                 let countryNameJSON = dataJSON["data"][country]["name"].stringValue                 print(countryNameJSON)                 //on ajoute ce nom au tabeleau de pays                 //self.countryArray.append(countryNameJSON)             }         }     } }}

Populating a UIPIckerView with remote JSON array

$
0
0

I am downloading a JSON Array from a remote server:

var colores = [Colores]()func downloadJSONColores(completed: @escaping () -> ()) {         let url = URL(string: "https://../colores.php")         URLSession.shared.dataTask(with: url!) { (data,response,error) in            print(data as Any)            print(response as Any)         if error == nil {             do {                 self.colores = try JSONDecoder().decode([Colores].self, from: data!)                 DispatchQueue.main.async {                     completed()                 }             }catch{             }         }         }.resume()     }

I have a struct class for Colores:

struct Colores:Decodable {    let id: Int    let nombre: String    let icono: String    let modelo: Int    let caracterista: Int}

What I need is to populate a PickerView with the decoded JSON objects, showing the field nombre as title and storing the field id from the pickerview selected item.

I am calling the downloadJSONColores method in viewDidLoad as follows:

downloadJSONColores {            coloresPV.reloadData()                     }

where coloresPV is my pickerView, but obviously this way of doing this only works for collectionViews, not for pickerViews. Which would be the best way to populate the pickerView while executing downloadJSONColores?

Poblar Picker View desde Firestore

$
0
0

tengo un proyecto en swift 4, dentro un campo de texto que quiero que llame a un picker view el cual debe mostrar datos desde firestore, pero no logro hacerlo...

Enumerando:1.- Abrir un picker view desde un campo de texto(esto creo ya lo he logrado, pero con data local)2.- Obtener datos desde firestore(logro obtener toda la colección, pero sin poder filtrarla, la data se compone de colección-->documentos-->campos y lo que deseo es mostrar solo los valores de uno de los campos)

Deseo poblar el picker view con el valor del campo buildingName de cada documento en la colección

De momento he buscado dentro de la documentación de google, pero no hay referencia. Agradezco su apoyo.

Viewing all 593 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>