Easy way to IT Job

IOS APP
Share on your Social Media

IOS APP

Published On: January 5, 2023

iOS App: Working with MultiComponent Picker

You have found the ideal blog if you are an experienced developer who is interested in how the MultiComponent picker functions. In this blog post, we’ll discuss how to add a multicomponent picker to our conversion iOS app to increase its functionality and how to use alerts to handle situations expertly.

The Primary Objective of this blog:

The keyboard must disappear when the person touches any part of the wallpaper. Gain expertise in MultiComponent Picker through our iOS Course in Chennai at Softlogic Systems.

Drag a button, then use the attributes inspector to change the button’s type to custom and the text color to clear.

Button's Type

Now, choose Editor > Arrange > Send to Back.

Editor &Amp; Arrange

Now, the button should be resized to accommodate the entire display.

Entire Display

The keyboard can now be hidden by clicking this button, which now functions as a background invisible button. Let’s create an IBAction for it, switch to assistant editor mode, and control + drag the object to ViewController.h. Click Connect after setting the Connection to Action and giving the name BackgroundButton.

Viewcontroller

This is how the view controller code currently appears.

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UIPickerViewDelegate, UIPickerViewDataSource>

@property (strong, nonatomic) IBOutlet UITextField *ValueTextField;

@property (strong, nonatomic) IBOutlet UIPickerView *picker2;

@property(strong,nonatomic) NSArray *data;

@property (strong, nonatomic) IBOutlet UILabel *ResultLabel;

– (IBAction)Convert:(UIButton *)sender;

– (IBAction)backgroundButton:(id)sender;

@end

Write the following code in ViewController.m after switching.

– (IBAction)backgroundButton:(id)sender {

[_ValueTextField resignFirstResponder];

[_picker2 resignFirstResponder];

[_ResultLabel resignFirstResponder];

}

When a touch is detected, the code instructs all other objects to cede the first responder status in this case. Run the iOS app now and observe. The keyboard will disappear when you touch the background, as you can see. Once you have finished typing, execute the backgroundButton method in the picker’s didselectRow() method to remove the keyboard. Consequently, this is the method code:

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

{

selectedValue = _data[row];

[self backgroundButton:0];

}

Now that the programme is more visually appealing, you can add a backdrop and perhaps even a nice button image.

Find an appropriate image first, of course, to do that! After that, place it in the Images.xcassets folder and modify the image’s global scaling from 1x to 2x.

Global Scaling

You may now improve on the iOS app’s aesthetics by adding a backdrop and perhaps even a nice button image.

Find a suitable image first, of course, before doing that! The picture should then be changed from 1x to 2x screen in universal mode after being added to the Images.xcassets folder.

Images Xcassets Folder

Test the iOS app’s functionality by running it.

Iphone 5S

Suppose I switch to an iPhone 5s.

Run The App

And now run the iOS app

Iphone 5S

We can observe that everything functions as intended in this situation. What if I wanted to give my button a background so that it looked more like a button? I would start by adding an IBOutlet for the convert button to the ViewController in order to accomplish that.

@property (strong, nonatomic) IBOutlet UIButton *convert;

adding the subsequent code to the viewDidLoad() function after that

self.convert.backgroundColor = [UIColor colorWithRed:0.4 green:0.8 blue:1.0 alpha:1.0];

[_convert setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

Let’s test our iOS app to see if it works as intended.

Iphone 5S

Okay, great! You probably also noticed that I shifted the locations of the result labels; I’ll explain why I did this in a moment.

We are aware that our programme only converts between Celsius and Fahrenheit in one direction. So how about including a few additional conversions or functions? To achieve this, we must add a further component to the UIPickerView that, when a unit is picked in the picker’s initial component, provides the proper selection.

We must add a new NSArray data2, which will house the data for the second component, in order to divide a picker into two parts. Create two constants to represent our two components as well. For the sake of programming simplicity, the left component in this case is stated to be 0 and the right component to be 1.

The format of your ViewController.h file is

#import <UIKit/UIKit.h># define data1comp 0# define data2comp 1

@interface ViewController : UIViewController<UIPickerViewDelegate, UIPickerViewDataSource,UIAlertViewDelegate>

@property (strong, nonatomic) IBOutlet UITextField *ValueTextField;

@property (strong, nonatomic) IBOutlet UIPickerView *picker2;

@property(strong,nonatomic) NSArray *data1;

@property (strong, nonatomic)NSArray *data2;

@property (strong, nonatomic) IBOutlet UILabel *ResultLabel;

@property (strong, nonatomic) IBOutlet UIButton *convert;

– (IBAction)Convert:(UIButton *)sender;

– (IBAction)backgroundButton:(id)sender;

@end

Now, in the ViewDidLoad() method, define the array data2. Now that we have access to both data sources, we need to be able to write code for the picker so that, when an item is selected from its first component, its second component changes to reflect the selected item’s value. The choice of the first component affects the second component.

To do this, we first create a dictionary to hold the keys and values. Data related to the first component of the picker is contained in keys, and data corresponding to the second component is contained in values.

– (void)viewDidLoad {

[super viewDidLoad];

_data1=[NSArray arrayWithObjects:@”Celsius”,@”Fahrenheit”,@”Meter”,@”Centimeter”, nil];

data2=[NSArray arrayWithObjects:@”Centimeter”,@”Meter”,@”Fahrenheit”,@”Celsius”,nil ];

dictionary= [NSDictionary dictionaryWithObjectsAndKeys:@”Celcius”,@”Farenheit”,
@”Farenheit”,@”Celcius”,@”Meter”,@”Centimeter”,@”Centimeter”,@”Meter”, nil];

self.view.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:(@”bg2.png”)]];

}

To ensure that both components have data filled in, we must now modify the data source and assign the current picker’s methods to the following.

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView

{

return 2;

}

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

{

if(component == data1comp)

{

return [self.data1 count];

}

return [self.data2 count];

}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component

{

if(component == data1comp)

{

return [self.data1 objectAtIndex:row];

}

return [self.data2 objectAtIndex:row];

}

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

{

[self backgroundButton:0];

if(component == data1comp)

{

NSString *data11=[_data1 objectAtIndex:row];

NSArray *a= [dictionary objectForKey:data11];

secondrow = [self.data2 indexOfObject:a];

[_picker2 selectRow:secondrow inComponent:data2comp animated:YES];

[_picker2 reloadComponent:data2comp];

selectedValue = data11;

selectedRow= row;

}

}

We retrieve the first component’s selected value in this didSelectRow() method, and then we provide that value as an argument to the dictionary’s objectForKey() method to retrieve the key’s matching value. The indexOfObject() method of the array is used to locate the corresponding location for the value in the second array, data2, and the result is stored as an integer value.

The picker method selectRow:row inComponent:component () subsequently receives this integer value. and use the reloadComponent command to reload the picker’s component ().

Once we’ve done so, whenever we choose one thing from the picker’s first component, the equivalent item in its second component will also be chosen.

The didSelectRow’s source code ()

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

{

[self backgroundButton:0];

if(component == data1comp)

{

NSString *data11=[_data1 objectAtIndex:row];

NSArray *a= [dictionary objectForKey:data11]

secondrow = [self.data2 indexOfObject:a];

[_picker2 selectRow:secondrow inComponent:data2comp animated:YES];

[_picker2 reloadComponent:data2comp];

selectedValue = data11;

selectedRow= row;

}

}

Run the iOS app now to see if the picker behaves as planned.

Iphone 5S

So let’s keep coding the convert button. Just two values, Celsius and Fahrenheit, had to match in the earlier picker in order for the outcome to be determined. The four values we now have are Celsius, Fahrenheit, Meter, and Centimeter. In order to calculate the value based on the selected row variable, I used a switch statement.

– (IBAction)Convert:(UIButton *)sender {

float val=[_ValueTextField.text floatValue];

NSLog(@”value %f”,val);

switch(selectedRow)

{

case 0:// Celsius to Fahrenheit

res=(val*1.8)+32;break;

case 1: // Fahrenheit to Celsius

res=(val-32)/1.8;break;

case 2: // Meter to Centimeter

res= val*100; break;

case 3://Centimeter to Meter

res=val*0.01; break;

default: res=0.0;

}

NSString *final= [NSString stringWithFormat:@”%.02f”,res];

_ResultLabel.text = final;

}

You can see if everything functions properly by running the iOS app.

Iphone 5S

We can now check for potential exceptions in our iOS app. For instance, the text field has no value. Alternatively, we are attempting the mathematically impossible conversion from Celsius to Meter or Centimeter. These kinds of situations are known as exceptions, and we must write code to manage them in order to prevent them.

Let’s fix the first type of error that can happen when our programme is running. In other words, we forget to enter the value that will be converted in the textfield. In this case, we must notify our users to enter the value before continuing.

The UIAlertView can be used for this. A method called showAlertWithMessage (NSString *) message can be created. This technique enables us to declare an alertView and finally show it on the screen by calling the show() method. The method’s code will look like this.

– (void)showAlertWithMessage:(NSString *) message {

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@”Error” message:message delegate:self cancelButtonTitle:nil otherButtonTitles:@”Okay”, nil];

alertView.tag = 100;

_ResultLabel.text=@”No Result”;

[alertView show];

}

When the user hits the convert button, this approach must now be referred to as conversion. No conversion should be performed without the value being entered. As a result, we must determine whether the length of the textfield is higher than or equal to zero in the method definition for convert. If so, convert; else, alert will be displayed. The convert button code would therefore look like this:

– (IBAction)Convert:(UIButton *)sender {

if([_ValueTextField.text length] <= 0)

{

[self showAlertWithMessage:@” Please enter the value”];

}

else

{

float res=0.0;

float val=[_ValueTextField.text floatValue];

NSLog(@”value %f”,val);

switch(selectedRow)

{

case 0:// Celsius to Fahrenheit

res=(val*1.8)+32;break;

case 1: // Fahrenheit to Celsius

res=(val-32)/1.8;break;

case 2: // meter to centimeter

res= val*100; break;

case 3://centimeter to meter

res=val*0.01; break;

default: res=0.0;

}

NSString *final= [NSString stringWithFormat:@”%.02f”,res];

_ResultLabel.text = final;

}

}

Run the iOS app now and attempt to click the convert button without adding any data into the text field.

Iphone 5S

The second kind of exception that could happen is if the value in the first component of the UIPickerView does not match the value in the second component. For this, we determine whether the row value of the second component’s currently selected component matches the row value returned by the method’s didSelectRow() delegate. Conversion is not feasible if the conditions are not met, but it is possible if the values match.

This logic can be put into practise as follows:

– (IBAction)Convert:(UIButton *)sender {

if([_ValueTextField.text length] <= 0)

{

[self showAlertWithMessage:@” Please enter the value”];

}

else

{

_ResultLabel.textColor= [UIColor blackColor];

float res=0.0;

NSInteger n =[_picker2 selectedRowInComponent:data2comp];

if(n==secondrow)

{

float val=[_ValueTextField.text floatValue];

NSLog(@”value %f”,val);

switch(selectedRow)

{

case 0:// Celsius to Fahrenheit

res=(val*1.8)+32;break;

case 1: // Fahrenheit to Celsius

res=(val-32)/1.8;break;

case 2: // meter to centimeter

res= val*100; break;

case 3://centimeter to meter

res=val*0.01; break;

default: res=0.0;

}

NSString *final= [NSString stringWithFormat:@”%.02f”,res];

_ResultLabel.text = final;

}

else

{

// code for displaying error.

_ResultLabel.textColor= [UIColor redColor];

_ResultLabel.text = @”Result cannot be calculated”;

}

}

After making your choice in the first component, run the programme to see the effect of altering the value there.

Run The Programme

The error warning saying the result cannot be calculated is visible. You’ll see that the error message is lengthy and was put in the same result label. This is the reason the label was shifted downward from its previous alignment.

Our conversion iOS app is now finished. The software can have additional features added as desired, and you can customize its aesthetic to suit your requirement.

Conclusion

Learn MultiComponent picker practically in our iOS Training in Chennai with IBM Certification at Softlogic Systems.

Share on your Social Media

Just a minute!

If you have any questions that you did not find answers for, our counsellors are here to answer them. You can get all your queries answered before deciding to join SLA and move your career forward.

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.