How do I reload/refresh the UIPickerView (with new data array) based on button press?

前端 未结 7 1623
抹茶落季
抹茶落季 2020-12-24 04:30

IF I wanted a picker, for states/provinces, i haven\'t seen an example, but I mocked up shown above, a picker for US/Can/Mex. wondering can you dynamically switch t

相关标签:
7条回答
  • 2020-12-24 05:17

    In your button press action,

    [self.pickerView selectRow:0 inComponent:0 animated:YES];
    
    0 讨论(0)
  • 2020-12-24 05:20

    Swift: xcode 6.1

    // reload the component of picker (Used this inside the trigger action or button)

    [self.pickerControl reloadAllComponents];
    
    0 讨论(0)
  • 2020-12-24 05:20

    Swift 3 & 4

    I had the same problem but no solution works,

    then i use DispatchQueue it works

    DispatchQueue.main.async(execute: {
            self.picker.delegate = self
            self.picker.dataSource = self
            if self.pickerData.count > 0 {
                self.pickerTextField.text = self.pickerData[0]
                self.pickerTextField.isEnabled = true
            } else {
                self.pickerTextField.text = nil
                self.pickerTextField.isEnabled = false
            }
        })
    
    0 讨论(0)
  • 2020-12-24 05:21

    You will have to implement the datasource and the delegate.

    once you press a button, set an array pointer to the appropriate array.

    than call [thePicker reloadAllComponents];

    -(IBAction) usButtonPressed:(id)sender{
        self.inputArray = self.usArray;
        [self.thePicker reloadAllComponents];
    }
    
    -(IBAction) mexicoButtonPressed:(id)sender{
        self.inputArray = self.mexicoArray;
        [self.thePicker reloadAllComponents];
    }
    

    the datasource methods:

    - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
    {
        return 1;
    }
    
    
    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
    {
        return [self.inputArray count];
    }
    

    the delegate methods:

    - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
    {
        return [self.inputArray objectAtIndex:row];
    }
    
    0 讨论(0)
  • 2020-12-24 05:23

    By calling

    thePicker.delegate = self;
    

    again, I was able to force refresh the pickerview with new info

    0 讨论(0)
  • 2020-12-24 05:23

    In swift 3,4,or 5 you just write in didSelectRow function like bellow

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    
    
            self.view.endEditing(false)
            yourPickerView.selectRow(0, inComponent: 0, animated: true)
            yourPickerView.reloadAllComponents();
    
    }
    
    0 讨论(0)
提交回复
热议问题