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

Swift - Horizontal UIPickerView

$
0
0

I'm trying to make a Horizontal Picker using Swift by rotating the UIPickerView and then rotating the label inside it, I tried also rotating the view inside it, instead of the label.

But in both ways I have the same result as shown in the image, the labels inside the picker are still not displayed as it is supposed to be.

Please take a look at the photo and the code,any ideas on how to fix this?

Horizontal Picker

@IBOutlet weak var myPicker: UIPickerView!var rotationAngle: CGFloat!var pickerArray: [String] = [String]()override func viewDidLoad() {    super.viewDidLoad()    rotationAngle = -90 * (.pi/180)    myPicker.transform = CGAffineTransform(rotationAngle: rotationAngle)    self.myPicker.delegate = self    self.myPicker.dataSource = self    pickerArray = ["Hello", "World", "What", "Where", "When", "How", "Hey", "Welcome", "Good", "Ok", "Bye", "World!"]    rotatePickerView(pickerView: myPicker)}func numberOfComponents(in pickerView: UIPickerView) -> Int {    return 1}func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {    return pickerArray.count}internal func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {    return pickerArray[row]}func rotatePickerView(pickerView : UIPickerView) {    myPicker.transform = CGAffineTransform(rotationAngle: rotationAngle)    myPicker.frame = CGRect(x: -150, y: myPicker.frame.origin.y, width: view.frame.width + 300, height: 200)}func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {    let label = UILabel()    label.font = UIFont(name: "Helvetica", size: 24)    label.font = UIFont.systemFont(ofSize: 24, weight: .regular)    label.minimumScaleFactor = 0.5    label.textAlignment = .center    label.textColor = UIColor.black    label.transform = CGAffineTransform(rotationAngle: 90 * (.pi / 180 ))    label.text = pickerArray[row]    return label}

Can I show a UIPickerView manually?

$
0
0

I am trying to implement a dropdown in form of a UIPickerView. It will have three components: (Currency, Charges, Days). Now, I can implement the currency and Days component easily, but I am not able to figure out how I can implement 'Charges' as Charges can vary from $1 to several 100 which obviously I cant input before hand. So, I was wondering is this possible to implement or it's just a foolish way to attempt this? Image is attached below which I am trying to implement.

enter image description here

Swift Dictionary UIPickerView (key) and (value) Swift

$
0
0

I'm currently developing an app using Swift where I use a UIPickerView. I want to set the value in the pickerView (myPickerView)

let PickerData = {"listOfGrouoc": {"1": "DDDDD","2": "SDDDDD","3": "TTTT"},"TypeOfGrpos": ["STTTTT","TTTTT"],"SubTypp": {"333": "Shh","334": "SSS","543": " dfdf"},"GropName": {"1": "test","2": "test"    }  }

Here is response comes from server i want to show group listOfGrouoc in pickerView

Code Below:-

In viewDidLoad I have:

Picker.delegate = selfPicker.dataSource = self

Then I have required methods:

func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {            return 1        }func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {            return PickerData.count        }func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {            return PickerData[row] trying to show SSSSS,DDDDD,GGGGG        }func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {       print(PickerData[row]) expecting only id Int Value    }

Question:- Can someone please explain to me how to set dict value in picker view title and when click on didSelectRow get dict key . Any help would be greatly appreciated.

Thanks in advance.

SwiftUI: Setting Picker line height

$
0
0

TL:DR

For large fonts, the lines in a Picker are overlapping. How do I change the Picker's line height? (Hint: the .lineSpacing modifier doesn't do it.)

See Also

This question is similar to that of Ejaaz, but his is so far unanswered.

The Problem

picker view

The Code

The following runnable code yields the above result. I don't really want different-sized lines, I just want the large fonts to fit properly. I have tried inserting Spacers, adding .frame modifiers here and there, .lineSpacing, padding() ... maybe just haven't found the right combination?

struct ContentView: View {    @State private var selected = 0    var body: some View {        Picker(selection: self.$selected, label: Text("Letters")) {            Text("A").font(.system(size: 30))            Text("B").font(.system(size: 40))            Text("C").font(.system(size: 50))            Text("D").font(.system(size: 60))            Text("E").font(.system(size: 70))            Text("F").font(.system(size: 80))        }    }}

How to Create Dynamic Textfield, Checkbox and Picker and add all the UI Controls in scrollView in Objective-C

$
0
0

How to Create Dynamic Textfield,Checkbox and Picker and add all the UIcontrols in scrollView
My Requirement:
I need to design my view like below:
enter image description here
Below is my API Response:

dictCustomFieldGroups: (        {        name = Name;        showtype = mandatory;        type = "Normal Text";    },        {        name = Age;        showtype = mandatory;        type = "Short Text";    },        {        name = Color;        showtype = optional;        type = Dropdown;        values =         (            Red,            Green,            Blue        );    },        {        name = Symptoms;        showtype = optional;        type = Checkbox;        values =         (            Cough,            Cold,            Fever        );    } )  

My code Implementation:
Currently I have created two UIViews using nib.
1) CustomTextField
2) CustomCheckBox
I have implemented the same code in both the views .m files, only loadNibNamed has changed.

- (id)initWithFrame:(CGRect)frame{    self = [super initWithFrame:frame];    if (self)    {        // No need to re-assign self here... owner:self is all you need to get        // your outlet wired up...        UIView* xibView = [[[NSBundle mainBundle] loadNibNamed:@"CustomCheckBox" owner:self options:nil] objectAtIndex:0];        // now add the view to ourselves...        [xibView setFrame:[self bounds]];        [self addSubview:xibView]; // we automatically retain this with -addSubview:    }    return self;}  

Below is my My ViewController's Implementation:

self->dictCustomFieldGroups = [[NSDictionary alloc] init];                self->dictCustomFieldGroups = [resJson valueForKeyPath:@"detail.customfieldgroups"];                NSLog(@"dictCustomFieldGroups: %@",self->dictCustomFieldGroups);                if ([self->dictCustomFieldGroups count] > 0) {                    float height = 0;                    for (int i = 0; i < self->dictCustomFieldGroups.count; i++) {                        //NSLog(@"name:%d  %@",i,[[self->dictCustomFieldGroups valueForKey:@"name"] objectAtIndex:i]);                       //NSLog(@"showtype:%d %@",i,[[self->dictCustomFieldGroups valueForKey:@"showtype"] objectAtIndex:i]);                        //NSLog(@"type:%d %@",i,[[self->dictCustomFieldGroups valueForKey:@"type"] objectAtIndex:i]);                        if ([[[self->dictCustomFieldGroups valueForKey:@"type"] objectAtIndex:i] isEqualToString:@"Normal Text"] || [[[self->dictCustomFieldGroups valueForKey:@"type"] objectAtIndex:i] isEqualToString:@"Short Text"]) {                            CustomTextField *myCustomView = [[CustomTextField alloc] initWithFrame:CGRectMake(0, i*90 + 10, 374, 90)];                            myCustomView.layer.borderColor = [UIColor lightGrayColor].CGColor;                            myCustomView.layer.borderWidth = 1.0f;                            myCustomView.layer.cornerRadius = 5;                            myCustomView.layer.masksToBounds = true;                            myCustomView.lblTitle.text = [VizsafeCommonUtil trimWhiteSpaceAndNewLine:[[self->dictCustomFieldGroups valueForKey:@"name"] objectAtIndex:i]];                            myCustomView.txtValue.placeholder = [NSString stringWithFormat:@"Enter the %@",[VizsafeCommonUtil trimWhiteSpaceAndNewLine:[[self->dictCustomFieldGroups valueForKey:@"name"] objectAtIndex:i]]];                            myCustomView.txtValue.returnKeyType = UIReturnKeyDone;                            myCustomView.txtValue.tag = i + 1;                            myCustomView.txtValue.delegate = self;                            [self.scView insertSubview:myCustomView atIndex:i];                            height += 90;                        } else if ([[[self->dictCustomFieldGroups valueForKey:@"type"] objectAtIndex:i] isEqualToString:@"Dropdown"]) {                        } else if ([[[self->dictCustomFieldGroups valueForKey:@"type"] objectAtIndex:i] isEqualToString:@"Checkbox"]) {                            CustomCheckBox *myCustomView = [[CustomCheckBox alloc] initWithFrame:CGRectMake(0, height + 10, 374, 90)];                            myCustomView.layer.borderColor = [UIColor lightGrayColor].CGColor;                            myCustomView.layer.borderWidth = 1.0f;                            myCustomView.layer.cornerRadius = 5;                            myCustomView.layer.masksToBounds = true;                            myCustomView.lblTitle.text = [VizsafeCommonUtil trimWhiteSpaceAndNewLine:[[self->dictCustomFieldGroups valueForKey:@"name"] objectAtIndex:i]];                            NSArray *arrChecks = [[self->dictCustomFieldGroups valueForKey:@"values"] objectAtIndex:i];                            /*for (NSString *strValue in arrChecks) {                                 NSLog(@"strValue: %@",strValue);                                myCustomView.lblValue.text = strValue;                            }                            [myCustomView.btnCheckbox setBackgroundImage:[UIImage imageNamed:@"checkbox-checked-white"]forState:UIControlStateSelected];                            //myCustomView.txtValue.tag = i + 1;                            [self.scView insertSubview:myCustomView atIndex:i];                            height += 90;*/                            CGFloat staticX         = 5;    // Static X for all buttons.                            CGFloat staticWidth     = 60;   // Static Width for all Buttons.                            CGFloat staticHeight    = 56;   // Static Height for all buttons.                            CGFloat staticPadding   = 5;                            for (int j = 0; j < [arrChecks count]; j++)                            {                                self->settButton = [UIButton buttonWithType:UIButtonTypeCustom];                                [self->settButton setTag:j];                                [self->settButton setFrame:CGRectMake((staticX + (j * (staticHeight + staticPadding))),5,staticWidth,staticHeight)];                                [self->settButton setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%i.png",j]] forState:UIControlStateNormal];                                [self->settButton addTarget:self action:@selector(ChkUnChk:) forControlEvents:UIControlEventTouchDown];                                [myCustomView insertSubview:self->settButton atIndex:j];                                //[myCustomView addSubview: self->settButton];                            }                            //[self.scView addSubview: myCustomView];                            [self.scView insertSubview:myCustomView atIndex:i];                                                       height += 90;                        }                    }                    self->_scView.contentSize = CGSizeMake(self.scParentView.frame.size.width, height);                    self.scView = [[UIScrollView alloc] initWithFrame:self.scParentView.frame];                    // now add our scroll view to the main view                    [self->_scParentView addSubview:self.scView];                } else {                    self.scParentView.hidden = TRUE;                }

iOS, UIPickerView create programmatically, empty view, delegates work

$
0
0

@Hey everybody,

I have trouble w/ UIPickerView. I'm planning to create a view controller which should allow user to specify the one of the next day. PickerView should show strings like "wed, 1 Dec", "thu, 2 dec", etcThe problem is PickerView is empty (PickerView doesn't show any string). In spite of delegates methods return necessary count of strings and the strings themselves.

Image of empty PickerView - LINK

Below is my code.

.h

@interface OMSDatePickerViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource>@property (nonatomic        ) NSInteger     amountOfDays;@property (nonatomic        ) CGFloat       cellHeight;@end

.m

#import "OMSDatePickerViewController.h"@interface OMSDatePickerViewController () {    NSMutableArray * dateForChoose;    NSInteger datePickerActiveIdx;    UIPickerView *dPicker;}@end- (void)viewDidLoad{    NSLog(@"viewDidLoad");    [super viewDidLoad];    // Do any additional setup after loading the view.    dateForChoose = [[NSMutableArray alloc] init];    dPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(5, 5, 200, 150)];      [self.view setFrame: CGRectMake(xPos, yPos, WIN_WIDTH, WIN_HEIGHT)];    [self.view setAlpha:1.0];    [self.view setBackgroundColor:[UIColor grayColor]];    [[self.view layer] setCornerRadius:5.0f];    [[self.view layer] setBorderWidth:2.0f];    [[self.view layer] setMasksToBounds:YES];    [self.view setContentMode:UIViewContentModeScaleToFill];    // Creating the list of dates    NSDateFormatter *df = [[NSDateFormatter alloc] init];    df.dateFormat = @"EEE',' dd MMM";    [dateForChoose removeAllObjects];    // Add some data for demo purposes.    NSDate *curDate = [NSDate date];    NSString *str;    for (NSInteger i = 0; i< amountOfDays; i++, curDate = [curDate dateByAddingTimeInterval:60*60*24]) {        str = [df stringFromDate:curDate];        [dateForChoose addObject:str];    }    [dPicker setDataSource: self];    [dPicker setDelegate: self];    dPicker.showsSelectionIndicator = YES;    [self.view addSubview:dPicker];    datePickerActiveIdx = 0;    NSLog(@"%@", dPicker);}

and delegates methods

// Number of components.-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{    return 1;}// Total rows in our component.-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{    NSLog(@"numberOfRowsInComponent: %d", [dateForChoose count]);    return [dateForChoose count];}// Display each row's data.-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{    NSString *str = [dateForChoose objectAtIndex: row];    NSLog(@"%@", [dateForChoose objectAtIndex: row]);    return [dateForChoose objectAtIndex: row];}// Do something with the selected row.-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{    NSLog(@"You selected this [%2d, %2d]: %@", row, component, [dateForChoose objectAtIndex: row]);    NSLog(@"count - %d", [dateForChoose count]);    datePickerActiveIdx = row;}

Interesting things when I try to rotate wheel "didSelectRow" is called and always return row == 0 and show:

[55215:c07] You selected this [ 0, 0]: Wed, 04 Dec

[55215:c07] count - 4

Any ideas?

Addition: the same code work well if it's copied to the implementation of internal function of some UIViewController. For example it's button event handler and the code is called by pressing this button.

WHAT IS IT???*

PS: working log

[18241:907] viewDidLoad[18241:907] <UIPickerView: 0x1cd944a0; frame = (5 5; 190 162); layer = <CALayer: 0x1cd94990>>[18241:907] viewWillAppear[18241:907] numberOfRowsInComponent: 4[18241:907] numberOfRowsInComponent: 4[18241:907] Wed, 04 Dec[18241:907] Thu, 05 Dec[18241:907] Fri, 06 Dec[18241:907] Sat, 07 Dec[18241:907] viewDidAppear

how i can have use my pickerview and click UIButon to have a text on my TextView

$
0
0

enter image description here

Hello

I make recipe apps.I configured my pickerView and gave it Recipe name.What I want is by clicking on my "Button", it's having the Recipe written on my "TextView".

A little help will be cool

thank you

Google traduction

UIPickerView - Numbers Range

$
0
0

How can I easily do a UIPickerView with : numberOfComponents 1 = number ; numberOfComponents 2 = label ; numberOfComponents 3 = number.Where number min (components 1) is always > number max (components 3). Maybe checking didSelectRow ?

Here is a screenshot I want to do uipickerview


Swift 5 PickerView Array Count is not working properly enough to calucate user BMI using Height and Weight

$
0
0

Used 2 PickerView Controllers with arrays to try to calculate user's BMI but the weight picker count gives me an Thread 1: Fatal error: Index out of range.

Is there anything I can do to fix this issue?[iPhone StoryBoard image]

        //Height, Country and Weight Labels and Pickers        @IBOutlet weak var bhLabel: UILabel!        @IBOutlet weak var weightCalLabel: UILabel!        @IBOutlet weak var heightbmiLabel: UILabel!        @IBOutlet weak var heightLabel: UILabel!        @IBOutlet weak var heightScrollMenu: UIPickerView!        @IBOutlet weak var weightLabel: UILabel!        @IBOutlet weak var weightScrollMenu: UIPickerView!        let heightToInches = (12...90).map { String($0) }        let weightOptions  =  (50...600).map  { String($0) }        func numberOfComponents(in pickerView: UIPickerView) -> Int {            return 1        }        func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {            if pickerView.tag == 31 {                return weightOptions.count            } else {                return heightToInches.count                }            }        func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {            if pickerView.tag == 30 {                return "\(heightToInches[row])"+" Inches"            }            else {                return "\(weightOptions[row])"+" Lbs"            }        }        func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {            if pickerView.tag == 30 {                heightLabel.text = String(heightToInches[row]) +" Inches"                heightbmiLabel.text = "(Height "+ String(heightToInches[row]) +" Inches)²"            }            if pickerView.tag == 31 {                weightLabel.text =  String(weightOptions[row]) +" lbs"                weightCalLabel.text = "Weight "+ String(weightOptions[row]) +" lbs"            }

Blockquote If I delete everything below then my app runs fine without any issues.

let stringHeight = self.heightToInches let IntHeight = Int(stringHeight[row])

            print(stringHeight[row])            let stringWeight = self.weightOptions

Blockquote let IntWeight = Int(stringWeight[row]) This is where i get an error but whenever I delete this line of code then my app does not experience the Fatal Error: Index out of Range Error

   If I delete everything below this line then I can use both pickerviews without any issues and select any             print("IntWeight = \(IntWeight!).")            let bmiconstant = 703            let CalWeight = Int(IntWeight!)            print("Cal Weight = \(CalWeight)")            let CalHeight = Int(IntHeight!)            print("CalHeight = \(CalHeight) ")            let heightSquared = CalHeight * CalHeight            print("HeightSquared = \(heightSquared)")            let WeightDividedByHeight: Double = Double(CalWeight) / Double(heightSquared)            let userBMI: Double = Double(bmiconstant) * Double(WeightDividedByHeight)            print("user bmi = \(userBMI)")            print("-------------------------")            print("")            print("")            print("")        }

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

$
0
0

enter image description here

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 the NSMutableArray for the UIPickerView and then have it somehow reload each time you click on US/Can/Mex buttons??? How do I go about doing this. What approach do I take. Looking for someone to point a beginner for a clue in the right direction.

How to create Custom UIDatepicker using UIPickerview in swift

$
0
0

I need to create pickerview which shows the date in following format dd MMM YYYY in pickerview how can i do that.

enter image description here

As i have no idea how to change display date format of uidatepickerview (only mode is available which is not enough for me)

So I decided to create custom picker using uipickerview with 3 components but i cannot validate exact result like FEB has only 28/29 other month have different days so how i can prevent user to select invalidate date like 31-feb.. etc..

How to create Flat UIDatePicker in swift

$
0
0

I need to create flat custom uidatepicker in swift to get same effect shown in image, I have tried some third party libraries but no one is providing flat view like shown in image. enter image description here

NOTE: DatePicker should have month in center also it must be look like flat not like cyclder view.

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndexedSubscript:]: index 10 beyond bounds [0 .. 9]'

$
0
0

In my code, three text fields are there for picker views. For example in the first text field, the user selects A+ blood group, in the second text field we don't want to display A+ blood group. Remaining items need to display. Text field 3 also same. For example, in text field 2 the user selects B+ blood group, in text field 3 B+ and A+ blood group needs to remove in array list. For example the user again selects the first text field and reselects another blood group like A- ve group re add the A+ blood group in array list. The same thing in text field2 and text field3. I got some exception. The exception is

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndexedSubscript:]: index 10 beyond bounds [0 .. 9]'

My json Response is:

question is :({Question = "What is your first pet's name?";QuestionID = 23;},{Question = "Who was your first grade teacher?";QuestionID = 24;},{Question = "What city were you born in?";QuestionID = 25;},{Question = "What was your childhood nickname?";QuestionID = 26;},{Question = "What was the name of your elementary school?";QuestionID = 27;},{Question = "Where does your nearest relative live?";QuestionID = 28;},{Question = "In what city or town was your first job?";QuestionID = 29;},{Question = "Which is your first car?  Edited ";QuestionID = 30;},{Question = "This is a test question - answer = ddi";QuestionID = 32;},{Question = "What is your Mother's maiden name?";QuestionID = 33;},{Question = "What is your Last name?";QuestionID = 35;},{Question = "What is the last 4 of your SSN?";QuestionID = 36;},{Question = "What is your Date of Birth? (MM/DD/YYYY)";QuestionID = 37;})

-(void)done:(id)sender

{

int row = [myPickerView selectedRowInComponent:0];

if (isBloodGroupFieldSelected) {

NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];

[dict setObject:QArray[row] forKey:@"title"];

NSInteger currentRow = row;

[dict setObject:[NSString stringWithFormat:@"%ld",currentRow] forKey:@"selectedIndex"];

[backUpArray replaceObjectAtIndex:0 withObject:dict];

selectedValue1 = QidArray[row];

bloodGroup.text = QArray[row];

[QArray removeObjectAtIndex:row];

[QidArray removeObjectAtIndex:row];

selectedItem1=bloodGroup.text;

NSLog(@"Selected row value 1 of Picker view is:%@",selectedItem1);

}

else if((!isBloodGroupFieldSelected) && (isGenderGroupFieldSelected))

{

NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];

[dict setObject:QArray[row] forKey:@"title"];

NSInteger currentRow = row;

[dict setObject:[NSString stringWithFormat:@"%ld",currentRow] forKey:@"selectedIndex"];

[backUpArray replaceObjectAtIndex:1 withObject:dict];

txtField1.text = QArray[row];

selectedItem2 = txtField1.text;

selectedValue2 = QidArray[row];

[QArray removeObjectAtIndex:row];

[QidArray removeObjectAtIndex:row];

}

else if(!isGenderGroupFieldSelected)

{

NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];

[dict setObject:QArray[row] forKey:@"title"];

NSInteger currentRow = row;

[dict setObject:[NSString stringWithFormat:@"%ld",currentRow] forKey:@"selectedIndex"];

[backUpArray replaceObjectAtIndex:2 withObject:dict];

txtField2.text= QArray[row];

selectedItem3= txtField2.text;

selectedValue3 = QidArray[row];

NSLog(@"Selected row value 3 of Picker view is.....:%@",selectedValue3);

NSLog(@"selected item value 1 of picker view is:%@",selectedItem3);

[QArray removeObjectAtIndex:row];

[QidArray removeObjectAtIndex:row];

}

[myPickerView selectRow:0 inComponent:0 animated:YES];

[bloodGroup resignFirstResponder];

[txtField1 resignFirstResponder];

[txtField2 resignFirstResponder];

}

-(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) {

eturn [QArray count];

}

else if(!isBloodGroupFieldSelected)

{

return [QArray count];

}

else if(!isGenderGroupFieldSelected)

{

return [QArray count];

}

return 0;

}

pragma mark - UIPickerViewDelegate

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

if (isBloodGroupFieldSelected) {

return QArray[row];

}

else if((!isBloodGroupFieldSelected) && (isGenderGroupFieldSelected))

{

return QArray[row];

}

else if(!isGenderGroupFieldSelected)

{

return QArray[row];

}

return 0;

}

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

}

  • (UIView *)pickerView:(UIPickerView *)thePickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{

UILabel *lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 310, 50)];

lblTitle.numberOfLines=2;

lblTitle.textColor=[UIColor blackColor];

lblTitle.font=[UIFont systemFontOfSize:20];

lblTitle.text=QArray[row];

return lblTitle;

}

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

if (textField == bloodGroup) {

isBloodGroupFieldSelected = YES;

NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithDictionary:[backUpArray objectAtIndex:0]];

NSString *str = [dict objectForKey:@"title"]?[dict objectForKey:@"title"]:@"";

NSInteger *index = (int)[NSString stringWithFormat:@"%@",[dict objectForKey:@"selectedIndex"]].intValue;

int count = (int) index;

if(str.length > 0){

[QArray insertObject:str atIndex:0];

}

}

else if (textField == txtField1){

isBloodGroupFieldSelected = NO;

isGenderGroupFieldSelected = YES;

NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithDictionary:[backUpArray objectAtIndex:1]];

NSString *str = [dict objectForKey:@"title"]?[dict objectForKey:@"title"]:@"";

NSInteger *index = (int)[NSString stringWithFormat:@"%@",[dict objectForKey:@"selectedIndex"]].intValue;

int count = (int) index;

if(str.length > 0){

[QArray insertObject:str atIndex:0];

}

}

else if (textField == txtField2){

isGenderGroupFieldSelected = NO;

isBloodGroupFieldSelected = NO;

NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithDictionary:[backUpArray objectAtIndex:2]];

NSString *str = [dict objectForKey:@"title"]?[dict objectForKey:@"title"]:@"";

NSInteger *index = (int)[NSString stringWithFormat:@"%@",[dict objectForKey:@"selectedIndex"]].intValue;

int count = (int) index;

if(str.length > 0){

[QArray insertObject:str atIndex:0];

}

}

[myPickerView reloadAllComponents];

}

  • (void)viewDidLoad{

[super viewDidLoad];

backUpArray = [[NSMutableArray alloc]init];

for(int i=0;i<=2;i++){

dict = [[NSMutableDictionary alloc]init];

[backUpArray insertObject:dict atIndex:i];

}

}

What’s the best way to let a PickerView determine arrays used in a different function?

$
0
0

I'm new to Swift and programming in general actually. I want to build a small iOS app and I'd really appreciate if someone could point me in the right direction with this question.

I have two Labels in my first ViewController, randomOne and Two, both of which texts already change every time you tab, by choosing a random word out of different arrays. In my second ViewController I've created a Picker View with two columns. I want the user to be able to choose, out of which two arrays of different words the Random Word Generator in my first ViewController chooses.

So if, for example, Picker Three and Picker One are selected in the Picker View, I want the Generator to choose from the arrays pickerThree and pickerOne in the shuffleClicked-function (Screenshot). So random(Number).text = picker(Number)[RandomWordGen(Number) at the bottom of the first ViewController has to be connected to the Picker View data somehow...

First ViewController:

import UIKitclass ViewController: UIViewController {    @IBOutlet var randomOne: UILabel!    @IBOutlet var randomTwo: UILabel!    override func viewDidLoad() {        super.viewDidLoad()    }    @IBAction func shuffleClicked(_ sender: Any) {        let pickerOne = ["One", "Two", "Three"]        let pickerTwo = ["Four", "Five", "Six"]        let pickerThree = ["Seven", "Eight", "Nine"]        let pickerFour = ["Ten", "Eleven", "Twelve"]        let RandomWordGenOne = Int(arc4random_uniform(UInt32(pickerOne.count)))        let RandomWordGenTwo = Int(arc4random_uniform(UInt32(pickerTwo.count)))        let RandomWordGenThree = Int(arc4random_uniform(UInt32(pickerThree.count)))        let RandomWordGenFour = Int(arc4random_uniform(UInt32(pickerFour.count)))        randomOne.text = pickerOne[RandomWordGenOne]        randomTwo.text = pickerTwo[RandomWordGenTwo]        }}

Picker View ViewController:

import UIKitclass SettingsViewController: UIViewController {    @IBOutlet weak var picker: UIPickerView!    let data = ["Picker One", "Picker Two", "Picker Three", "Picker Four"]    override func viewDidLoad() {        super.viewDidLoad()        picker.dataSource = self        picker.delegate = self    }}extension SettingsViewController: UIPickerViewDataSource {    func numberOfComponents(in pickerView: UIPickerView) -> Int {        return 2    }    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {        return data.count    }}extension SettingsViewController: UIPickerViewDelegate {    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {        return data[row]    }}

Thanks for any suggestions.

UiPickerview values displayed as question mark ("?")in swift - But getting the correct value while assigning it to a textBox

$
0
0

//I am able to see the correct value in the text box upon scrolling down the picker view. But the picker view display is coming as "?" (question marks). I am confused with where I need to assign the pickerview as input view to the textbox . But still that won't make any sense to the error I am facing right .

I am using Xcode 9 and Swift 3.2.

class BillDetailsViewController: UIViewController ,UITextFieldDelegate,UIPickerViewDelegate,UIPickerViewDataSource{  //Variables  Declaration  //Picker view outlet  @IBOutlet var datePickerView: UIPickerView!  //Picker view datasource - integer array  var integerArray = [Int](1899...2500)  //Textbox where picked value to be shown  @IBOutlet var txtPaidYear: UITextField!  //ViewLoad  override func viewDidLoad() {    super.viewDidLoad()    self.hideKeyboardWhenTappedAround()    datePickerView.isHidden = true    datePickerView.reloadAllComponents()    datePickerView.dataSource = self    datePickerView.delegate = self    txtPaidYear.inputView = datePickerView  }  //picker view delegate functions  public func numberOfComponents(in pickerView: UIPickerView) -> Int {    return 1  }  public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {    return integerArray.count  }  public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {    let pickerValue: String = String(integerArray[row])    return pickerValue  }  public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {    txtPaidYear.text = String(integerArray[row])    self.datePickerView.reloadAllComponents()  }}

Constraints error when using a UIPickerView

$
0
0

Whenever I click on one of the pickerviews that I create, I get the following error logged to the console:

[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.     (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)

I know that this error usually happens when there are conflicting constraints but I don't see what the conflicting constraints would be in this case. The pickerview still works correctly but I still would like to get rid of this error.

code:

@IBAction func showDatePicker(_ sender: PickerField){        let datePicker = UIDatePicker        let datePickerField = sender        datePicker.translatesAutoresizingMaskIntoConstraints = false        datePicker.datePickerMode = .time        let toolbar = UIToolbar()        toolbar.translatesAutoresizingMaskIntoConstraints = false        toolbar.sizeToFit()        let finishedButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(donedatePicker))        finishedButton.tag = sender.tag        let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)        let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelDatePicker))        cancelButton.tag = sender.tag        toolbar.setItems([cancelButton,spaceButton,finishedButton], animated: false)        datePickerField.inputView = datePicker        datePickerField.inputAccessoryView = toolbar    }

(FYI, I've tried turning translatesAutoResizingMaskIntoConstraints on and off for both the picker and toolbar and the error still occurs)

How to get picker view with Done button on Button click instead of textfield Swift5? [duplicate]

$
0
0

I am trying to get Picker view with done button so far i have achieving this on click on textfiled. but it has some disadvantage. After getting value we can able to edit that textfield.Is this possible to get picker on button click and picker should have Done button on toolbar?

 designationPicker = UIPickerView()        designationPicker.tag = 2        self.selectedDesignationTextFiled.inputView = designationPicker        designationPicker.selectRow(2, inComponent:0, animated:true)        self.designationPicker.delegate = self        self.designationPicker.dataSource = self        let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: 320, height: 44))        toolBar.tintColor = UIColor.gray        let doneBtn = UIBarButtonItem(title: NSLocalizedString("done", comment: ""), style: .done, target: self, action: #selector(showSelectedDesignation))        let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)        toolBar.items = [space, doneBtn]        self.selectedDesignationTextFiled.inputAccessoryView = toolBar

PIckerview array from URL API - objective c

$
0
0

I am a new in objective c. I tried to find a solution for my app for pickerview. But nothing work for me. I need data from mysql column called teacher_id. API works fine and return data. But I can not see teacher_id in pickerview. Any suggestion? Thank you very much.

MY .h

@interface Message2VC : BaseVC<UIAlertViewDelegate,YBPopupMenuDelegate,UIPickerViewDataSource, UIPickerViewDelegate>{IBOutlet UIPickerView *singlePicker;}

My .m

@interface Message2VC (){ NSArray *pickerData;}@end- (void)viewDidLoad {[super viewDidLoad];pickerData = [[NSMutableArray alloc]init];NSDictionary *dicParameters = @{                                @"school_id":SCHOOL_ID                                };[self postResponseFromURL:[NSString stringWithFormat:@"%@%@",URL_API_HOST_BASE,API_STUDENT_FEES] withParams:[NSMutableDictionary dictionaryWithDictionary:dicParameters] progrss:^(NSProgress *uploadProgress) {} success:^(NSURLSessionDataTask *task, id responseObject, bool isSuccess) {     NSLog(@"Response is:%@",responseObject);     if (![responseObject valueForKey:@"data"]) {         NSRange range;         NSString *strAlert = [responseObject valueForKey:@"error"];         while ((range = [strAlert rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)             strAlert = [strAlert stringByReplacingCharactersInRange:range withString:@""];         [[[UIAlertView alloc]initWithTitle:@"App" message:strAlert delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];     }     else{         pickerData = [responseObject objectForKey:@"data"];     } } failure:^(NSURLSessionDataTask *task, NSError *error) { } show Loader:YES hideLoader:YES];}- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {return 1;}- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {return [self->pickerData count];}- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{return self->pickerData[row][@"teacher_id"];}

Back button refreshes/reloads uipickerview content

$
0
0

I downloaded a project that I am trying to learn how to use SQLite3 with.The way the author wrote it, they use a segue to move from a screen with a pickerview and a play button to the mainVC where there is a game. If the user wants to save the game, instead of unwinding the segue, the author adds another segue to go back to the previous controller calling:

@IBAction func mainMenu(){    sqlite3_close(db)    sqlite3_close(db2)    //switch to picker view    performSegue(withIdentifier: "mainMenuSegue", sender: nil)}

It appears that the mainVC this function is in, is modally presented.In my experimenting/learning, I embedded the whole project in a navigation controller, hence having a back button to move from the mainVC to the picker view controller.

Is there a way to accomplish the above function with the back button? Currently pressing the back button will take me to the picker, but does not reload the picker data if I save a game. I have to go one more back and return to the picker view to get the reloaded data.

Thanks

How to make a timezone Picker in SwiftUI?

$
0
0

I m new to SwiftUI. I want to make a TimeZone PickerView for my example project.

Just like this picture shown...

After a few day works, I still cannot find a way to achieve my goal, including timezone search bar. I don't know why my code is always stuck. After I choose the first option, and I cannot choose other options again. In this situation, I cannot even click the TimeZone Picker area anymore. It's just stuck without reaction...

Here is my code for now:

    struct myPicker: View {    var timezone_area = ["TimeZ1", "TimeZ2", "TimeZ3", "TimeZ4", "TimeZ5", "TimeZ6", "TimeZ7", "TimeZ8", "TimeZ9", "TimeZ10"]    @State var TZPickerIndex: Int = 0    var body: some View {        NavigationView {            Form {                Section {                    Picker(selection: $TZPickerIndex, label: Text("TimeZone")) {                        ForEach(0 ..< timezone_area.count) {                            Text(self.timezone_area[$0]).tag($0)                        }                    }                }.padding()            }        }    }}

May somebody tell me that how to make it or which kinds of keyword should I use / search? Thanks for help.

Viewing all 593 articles
Browse latest View live


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