Set a default value for UIPickerView in Swift?
This is the code I have used in one of my apps:
// Declare the outlet to the picker in your storyboard
@IBOutlet var myPicker: UIPickerView!
//...
override func viewDidLoad() {
//...
myPicker.selectRow(row, inComponent: 0, animated: true)
}
Obviously, replace row
and 0
with whatever values you want.
Hope this Helps!
Set a default Value of a UIPickerView: index beyond bounds
Index starts from 0
. So you should modify it to this:
spinner.selectRow(3, inComponent: nivel, animated: true)
Set default value of UIPickerView when UITextField is touched
Implement the textFieldDidBeginEditing
text field delegate method and set the text field's text if it doesn't already have a value.
func textFieldDidBeginEditing(_ textField: UITextField) {
if textField.text!.isEmpty {
// set the text as needed
}
}
UIPickerView default row
Set the picker view's selected row to whatever initial row you want in the viewDidLoad
method. Here's Swift 3 code. Adjust as needed for Swift 2.
self.picker.selectRow(8, inComponent: 0, animated: false)
How to set a default Value of a UIPickerView
TL:DR version:
//Objective-C
[self.picker selectRow:2 inComponent:0 animated:YES];
//Swift
picker.selectRow(2, inComponent:0, animated:true)
Either you didn't set your picker to select the row (which you say you seem to have done but anyhow):
- (void)selectRow:(NSInteger)row inComponent:(NSInteger)component animated:(BOOL)animated
OR you didn't use the the following method to get the selected item from your picker
- (NSInteger)selectedRowInComponent:(NSInteger)component
This will get the selected row as Integer from your picker and do as you please with it.
This should do the trick for yah. Good luck.
Anyhow read the ref:
https://developer.apple.com/documentation/uikit/uipickerview
EDIT:
An example of manually setting and getting of a selected row in a UIPickerView:
the .h file:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>
{
UIPickerView *picker;
NSMutableArray *source;
}
@property (nonatomic,retain) UIPickerView *picker;
@property (nonatomic,retain) NSMutableArray *source;
-(void)pressed;
@end
the .m file:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize picker;
@synthesize source;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
self.view.backgroundColor = [UIColor yellowColor];
self.source = [[NSMutableArray alloc] initWithObjects:@"EU", @"USA", @"ASIA", nil];
UIButton *pressme = [[UIButton alloc] initWithFrame:CGRectMake(20, 20, 280, 80)];
[pressme setTitle:@"Press me!!!" forState:UIControlStateNormal];
pressme.backgroundColor = [UIColor lightGrayColor];
[pressme addTarget:self action:@selector(pressed) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:pressme];
self.picker = [[UIPickerView alloc] initWithFrame:CGRectMake(20, 110, 280, 300)];
self.picker.delegate = self;
self.picker.dataSource = self;
[self.view addSubview:self.picker];
//This is how you manually SET(!!) a selection!
[self.picker selectRow:2 inComponent:0 animated:YES];
}
//logs the current selection of the picker manually
-(void)pressed
{
//This is how you manually GET(!!) a selection
int row = [self.picker selectedRowInComponent:0];
NSLog(@"%@", [source objectAtIndex:row]);
}
- (NSInteger)numberOfComponentsInPickerView:
(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
return [source count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView
titleForRow:(NSInteger)row
forComponent:(NSInteger)component
{
return [source objectAtIndex:row];
}
#pragma mark -
#pragma mark PickerView Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
inComponent:(NSInteger)component
{
// NSLog(@"%@", [source objectAtIndex:row]);
}
@end
EDIT for Swift solution (Source: Dan Beaulieu's answer)
Define an Outlet:
@IBOutlet weak var pickerView: UIPickerView! // for example
Then in your viewWillAppear or your viewDidLoad, for example, you can use the following:
pickerView.selectRow(rowMin, inComponent: 0, animated: true)
pickerView.selectRow(rowSec, inComponent: 1, animated: true)
If you inspect the Swift 2.0 framework you'll see .selectRow defined as:
func selectRow(row: Int, inComponent component: Int, animated: Bool)
option clicking .selectRow in Xcode displays the following:
Can't set default value UIPicker swift 2
Updated your code.
You didn't set the pickerView.dataSource!
If i understood your question, you want an element to be selected by default, other than element at index 0.
I also added that.
import UIKit
class CustomCell: UITableViewCell, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var answer: UITextField!
var delegate: QuestionSelectorCellDelegate?
var pickOption: [String] = []
var pickerView:UIPickerView = UIPickerView()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
@IBAction func editBeginQuestionSelectorCell(sender: UITextField) {
pickerView = UIPickerView()
pickerView.delegate = self
// --- Thats what I added ---
pickerView.dataSource = self
let indexOfDefaultElement = 1 // Make sure that an element at this index exists
pickerView.selectRow(indexOfDefaultElement, inComponent: 0, animated: false)
sender.inputView = pickerView
}
func displayBlock(block: Block){
if block.answers != nil {
pickOption = block.answers! // block.answers! = ["blue","red","green"] for example
}
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickOption.count
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return pickOption[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if row < pickOption.count {
answer.text = pickOption[row]
delegate?.updateQuestionSelectorCell(self, rep: pickOption[row])
}
}
}
Can't select default value of pickerView
if let index = MenuViewController.subjectsArray.index(where: {
$0.nameSubject == "Matematica"
}) {
self.subjectsMenu.selectRow(index, inComponent: 0, animated: true)
}
RxSwift: Set initial value for UIPickerView
Actually, using UIPickerView own method is fine;
mPicker.selectRow(defaultRowIndex, inComponent: 0, animated: false)
Related Topics
Binary Operator Cannot Be Applied to Operands of Type Int and Int? Swift 3
Xcode 8.3 Can't Support Swift 2.3
Inconsistent Scenekit Framerate
Ios8 Custom Keyboard - Copy & Paste to Uipasteboard
Why Can't We Use Protocol 'Encodable' as a Type in the Func
How Is Optional Binding Used in Swift
How to Get Random Element from a Set in Swift
How to Use Sf Rounded Font in Swiftui
How to Execute Code Once and Only Once in Swift
What Determines Whether a Swift 5.5 Task Initializer Runs on the Main Thread
Listing All Files in a Folder Recursively with Swift
Value of Optional Type Cgfloat Not Unwrapped Error in Swift
Optional Field Type Doesn't Conform Protocol in Swift 3
How to Change Navigation Bar & Back Button Colour iOS 15