Reputation: 11
I am working in Xcode 7 using Swift 2.
I have my UIPickerViews setup in textfields and they are all working as they should. I close the pickerviews using:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
pickerOptions.resignFirstResponder()
(etc.)
}
My issue is that I have one pickerview that I want to be a "presets" menu that will update 3 regular textfield inputs with a set of values by selecting a pickerview value without the need to update the values with a button. I'm not entirely sure how to go about this, as I am not very familiar with delegates yet (if it even involves them). I'm really at a lost on how to update/refresh the ViewController.
I would guess that it has something to do with textFieldDidEndEditing
(since I have these classes already setup from setting up the UIPickerView: UIPickerViewDataSource
, UIPickerViewDelegate
, UITextFieldDelegate
) Any help is appreciated :)
Upvotes: 1
Views: 90
Reputation: 9044
It's all about delegates. I understand you have a pickerView that should set the content of some textFields upon user selection. The pickerView is a stock object that needs to tell your class what's going on without knowing anything specific about your class. It does this by saying, if you implement this protocol that I define, then I will call your functions to let you know. In the case of pickerView, the related protocol is UIPickerViewDelegate
, and it exposes a property called delegate
that can only be set to an object that implements the protocol. If the pickerView's delegate is set, it will call that object's pickerView:didSelectRow:inComponent:
function when the user scrolls the pickerView.
You just need to create an object that will conform to the UIPickerViewDelegate
protocol, and set the pickerView's delegate
property accordingly. More often than not you will just add this ability to your viewController, along the lines of:
class viewController: UIViewController, UIPickerViewDelegate {
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
// Now you can update the textField(s)
}
}
Note that the definition of pickerView:didSelectRow:inComponent:
is marked as optional. This means if you say you implement UIPickerViewDelegate
, but don't define it, the compiler will not let you know. This can be confusing if you accidentally misspell it or get the signature wrong - you will think it's defined but it will never get called.
Upvotes: 1
Reputation: 2194
You could implement the delegate method:
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
//put your code here
}
that belongs to the UIPickerViewDelegate
protocol.
To see documentation of a protocol on XCode option
+ click on the name of the protocol.
Upvotes: 0