iOS : Radio Button Programatically Without using any Image - ios

I have been working on creating custom ui controls and want to know how to add radio button to UIView programatically.
I only found one solution but it is for mac osx application control.
Image of required result is given as.
LIMITATION
Not want to use image.
Thanks.

Radio button - Set corner radius and board color as below. Take three button in ViewController.h file
#property(nonatomic,retain) IBOutlet UIButton *btn1;
#property(nonatomic,retain) IBOutlet UIButton *btn2;
#property(nonatomic,retain) IBOutlet UIButton *btn3;
- (IBAction)ClickBtn1:(id)sender;
- (IBAction)ClickBtn2:(id)sender;
- (IBAction)ClickBtn3:(id)sender;
And in ViewDidLoad method.
- (void)viewDidLoad
{
[super viewDidLoad];
self.btn1.layer.cornerRadius = 10;
self.btn1.layer.borderColor = [[UIColor blackColor] CGColor];
self.btn2.layer.cornerRadius = 10;
self.btn2.layer.borderColor = [[UIColor blackColor] CGColor];
self.btn3.layer.cornerRadius = 10;
self.btn3.layer.borderColor = [[UIColor blackColor] CGColor];
// default
[self.btn1 setTitle:#"." forState:UIControlStateNormal];
[self.btn2 setTitle:#"" forState:UIControlStateNormal];
[self.btn3 setTitle:#"" forState:UIControlStateNormal];
}
Button Action on click.
- (IBAction)ClickBtn1:(id)sender
{
[self.btn1 setTitle:#"." forState:UIControlStateNormal];
[self.btn2 setTitle:#"" forState:UIControlStateNormal];
[self.btn3 setTitle:#"" forState:UIControlStateNormal];
}
- (IBAction)ClickBtn2:(id)sender
{
[self.btn2 setTitle:#"." forState:UIControlStateNormal];
[self.btn1 setTitle:#"" forState:UIControlStateNormal];
[self.btn3 setTitle:#"" forState:UIControlStateNormal];
}
- (IBAction)ClickBtn3:(id)sender
{
[self.btn3 setTitle:#"." forState:UIControlStateNormal];
[self.btn1 setTitle:#"" forState:UIControlStateNormal];
[self.btn2 setTitle:#"" forState:UIControlStateNormal];
}
in Your StoryBoard button View set as below height and Width (20,20) of the button. Take title name Dot (.) and its font size System 44.0and set Edge as below image.
Your Radio button is :

Related

How to reuse properties

I have many different buttons in my app, yet most of them have the same properties assigned to them:
login = [[UIButton alloc]initWithFrame:CGRectMake(8, CGRectGetMaxY(password.frame) + 16, loginView.frame.size.width - 16, 40)];
[login setTitle:#"Login" forState:UIControlStateNormal];
[login.titleLabel setFont:[UIFont fontWithName:#"Avenir Next" size:18]];
[login setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[login setTitleColor:[UIColor colorWithWhite:0.7 alpha:1] forState:UIControlStateHighlighted];
[login setTitleColor:[UIColor colorWithWhite:0.5 alpha:1] forState:UIControlStateDisabled];
Is there any way to create a class or something of a button that already has these default properties assigned? So I could simply go something like:
CustomButtom *btn = [CustomButton alloc]init];
Then the btn will have all of the above properties assigned?
Thanks.
Another way of handling this, is you can create a private method that will return the UIButton with the same properties. I think creating a subclass of UIButton is a little unnecessary.
You can do this by creating a CustomButton class
Xcode -> New File -> Cocoa Touch Class -> Next -> Name Your Button-> Select Subclass of UIButton
CustomButton.h file
#import <UIKit/UIKit.h>
#interface CustomButton : UIButton
#end
CustomButton.m file
#import "CustomButton.h"
#implementation CustomButton
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
//login = [[UIButton alloc]initWithFrame:CGRectMake(8, CGRectGetMaxY(password.frame) + 16, loginView.frame.size.width - 16, 40)];
[self setTitle:#"Login" forState:UIControlStateNormal];
[self.titleLabel setFont:[UIFont fontWithName:#"Avenir Next" size:18]];
[self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[self setTitleColor:[UIColor colorWithWhite:0.7 alpha:1] forState:UIControlStateHighlighted];
[self setTitleColor:[UIColor colorWithWhite:0.5 alpha:1] forState:UIControlStateDisabled];
}
#end
Now, Call you button
CustomButton *customButton = [[CustomButton alloc]initWithFrame:CGRectMake(8, CGRectGetMaxY(password.frame) + 16, loginView.frame.size.width - 16, 40)];
[customButton addTarget:self action:#selector(loginButtonPressed:) forControlEvents:UIControlEventTouchDown];
[YourView addSubview:customButton];
You've got two options:
Make a function that you can pass in a UIButton to that sets the properties for you
Write a Category for UIButton that does the same as the above. Categories allow you to add functionality to a class without subclassing. See https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html
Yes. You can subclass the UIButton. When you override the init method setting the properties you could get the button's with the same properties.

How to change title color and background color of dynamic UIButton when clicked and first button should be selected as default?

I have a view and I created some 8 dynamic buttons programmatically in that. The title color of buttons is white color. I want to change color of button title to green color when it is clicked. And if i click any other button, the previously clicked button title color should become white and current button title color should become green.
I have used the following code and its working properly for changing the color of previous button and now I want the first button to be in selected mode as default and first button should be changed when another button is clicked.
- (void)viewDidLoad
{
_examsListDict1 = [[NSMutableDictionary alloc]init];
_examsListDict1[#"Exam Name"] = #"JEE Mains";
.........so on another 4 dictionaries
_examsListArray = [[NSMutableArray
alloc]initWithObjects:_examsListDict1,_examsListDict2,_examsListDict3,_examsListDict4,_examsListD
ict5, nil];
NSUInteger i;
int xCoord=0;
int yCoord=0;
int buttonWidth=120;
int buttonHeight=50;
int buffer = 1;
for (i = 0; i <[_examsListArray count]; i++)
{
aButton = [UIButton buttonWithType:UIButtonTypeCustom];
aButton.frame = CGRectMake(xCoord, yCoord,buttonWidth,buttonHeight );
[aButton setTitle:[[_examsListArray objectAtIndex:i] objectForKey:#"Exam Name"]
forState:UIControlStateNormal];
[aButton setTag:i];
[aButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[aButton setBackgroundColor:[UIColor colorWithRed:250.0f/255.0f green:255.0f/255.0f
blue:221.0f/255.0f alpha:1]];
[aButton addTarget:self action:#selector(whatever:)
forControlEvents:UIControlEventTouchUpInside];
[_buttonsHorizontalScrollView addSubview:aButton];
xCoord += buttonWidth + buffer;
}
[_buttonsHorizontalScrollView
setContentSize:CGSizeMake(aButton.frame.size.width*_examsListArray.count+203, yCoord)];
}
- (void)whatever:(id)sender
{
UIButton *tempBtn = (UIButton *)sender;
[aButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[aButton setBackgroundColor:[UIColor colorWithRed:250.0f/255.0f green:255.0f/255.0f
blue:221.0f/255.0f alpha:1]];
aButton = tempBtn;
[aButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[aButton setBackgroundColor:[UIColor colorWithRed:133.0f/255.0f green:169.0f/255.0f
blue:83.0f/255.0f alpha:1]];
}
No I just want the first button to be selected as default when the view is loaded and whenever I select the other button it should change to deselected color.
if ([aButton tag] == 0)
{
[aButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[aButton setBackgroundColor:[UIColor colorWithRed:133.0f/255.0f green:169.0f/255.0f
blue:83.0f/255.0f alpha:1]];
}
I have used the above code to select as first button as default but first button is not getting changed when other button is clicked and it is changing only when the first button is clicked again due to this aButton = tempBtn.How to do that?
I suggest you to set the selected status title color of all your buttons and then add them to an array. Then when you press one of them just change their status, no need to handle colors or keep track of the currently selected button.
#property (strong, nonatomic) NSMutableArray *yourButtons;
- (void)viewDidLoad {
[super viewDidLoad];
_examsListDict1 = [[NSMutableDictionary alloc]init];
_examsListDict1[#"Exam Name"] = #"JEE Mains";
.........so on another 4 dictionaries
_examsListArray = [[NSMutableArray alloc] initWithObjects:_examsListDict1,_examsListDict2,_examsListDict3,_examsListDict4,_examsListDict5, nil];
NSUInteger i;
int xCoord=0;
int yCoord=0;
int buttonWidth=120;
int buttonHeight=50;
int buffer = 1;
// Generate background images
//
UIImage *backgroundImage = [self imageWithColor:[UIColor colorWithRed:250.0f/255.0f green:255.0f/255.0f blue:221.0f/255.0f alpha:1]];
UIImage *selectedBackgroundImage = [self imageWithColor:[UIColor colorWithRed:133.0f/255.0f green:169.0f/255.0f blue:83.0f/255.0f alpha:1]];
// Initialize your array
//
self.yourButtons = [[NSMutableArray alloc] init];
for (i = 0; i < [_examsListArray count]; i++) {
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
aButton.frame = CGRectMake(xCoord, yCoord,buttonWidth,buttonHeight );
[aButton setTitle:[[_examsListArray objectAtIndex:i] objectForKey:#"Exam Name"] forState:UIControlStateNormal];
[aButton setTag:i];
[aButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[aButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
[aButton setBackgroundImage:backgroundImage forState:UIControlStateNormal]
[aButton setBackgroundImage:selectedColorImage forState:UIControlStateSelected]
[aButton addTarget:self action:#selector(whatever:) forControlEvents:UIControlEventTouchUpInside];
[_buttonsHorizontalScrollView addSubview:aButton];
xCoord += buttonWidth + buffer;
// Select the first one
//
if (i == 0)
aButton.selected = YES;
// Add your newly created button to the array
//
[self.yourButtons addObject:aButton];
}
[_buttonsHorizontalScrollView setContentSize:CGSizeMake(aButton.frame.size.width*_examsListArray.count+203, yCoord)];
}
- (void)whatever:(id)sender {
for (UIButton *button in self.yourButtons) {
// Toggle selected flag
//
button.selected = button == sender;
}
}
+ (UIImage *)imageWithColor:(UIColor *)color {
// http://stackoverflow.com/a/24665476/1835155
//
CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
TRUEThe unpressed button is UIControlStateNormal while the pressed button is UIControlStateSelected so set the colours you want based on the State. You typically do this in ViewDidload before anyone has a chance to use it - Below is a sample setup:
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setSelected:YES];
button.frame = CGRectMake(x, y, width, height);
[button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];
[button setTitle:#"Button Title" forState:UIControlStateNormal];
[button addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[button setBackgroundImage:[UIImage imageNamed:#"button.png"] forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:#"buttonActive.png"] forState:UIControlStateSelected];
[button setBackgroundImage:[UIImage imageNamed:#"buttonActive.png"] forState:UIControlStateHighlighted];
[button setBackgroundImage:[UIImage imageNamed:#"buttonActive.png"] forState:UIControlStateDisabled];
I believe what you should be doing when the trigger button is clicked is to just set the state to selected
- (IBAction)touchDown:(id)sender {
if (sender == trigger_button) {
[button setHighlighted:TRUE];
[button setSelected:TRUE];
}
In order to change the first button state when another button is clicked you have to "fake" a touch event. In the selector method of the other button do this:
For Example:
-(void)thirdButtonClicked:(id) sender
{
[firstButton sendActionsForControlEvents: UIControlEventTouchUpInside];
}

Toggle Button Image

I have multiple of buttons.
They all load in the viewDidLoad. I want it so once one button has been pressed, it changes to the other image.
So Img1 loads via the viewDidload, then once it's been pressed, it goes to Img2
This is my current code which i have tried:
In the viewdidload:
btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
[btn1 setFrame:CGRectMake(367, 117, 97, 25)];
[btn1 setImage:[UIImage imageNamed:#"img1.png"] forState:UIControlStateNormal];
[btn1 addTarget:self action:#selector(playSound:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn1];
In the ibaction (which i tried, but im guessing)
-(IBAction)ButtonAction
{
if (btn1==0)
{
btn1=1;
[btn1 setImage:[UIImage imageNamed:#"img1.png"] forState:UIControlStateNormal];
}
else
{
[btn1 setImage:[UIImage imageNamed:#"img2.png"] forState:UIControlStateNormal];
btn1=0;
}
}
Thanks for the help
You need to make sure you are hooking up your UIButton to the proper selector. Also, I would use an #property or a global / instance variable to track which image is currently in the UIButton. Here's some code that should do the trick:
//... in #interface
#property (nonatomic, strong) NSString *btn1ImageName;
- (void)viewDidLoad {
[super viewDidLoad];
// ...
self.btn1ImageName = #"img1.png";
btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
[btn1 setFrame:CGRectMake(367, 117, 97, 25)];
[btn1 setImage:[UIImage imageNamed:self.btn1ImageName] forState:UIControlStateNormal];
[btn1 addTarget:self action:#selector(toggleImage:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn1];
}
- (void)toggleImage:(UIButton *)btn1 {
self.btn1ImageName = ([self.btn1ImageName isEqualToString:#"img1.png"]) ? #"img2.png" : #"img1.png";
[btn1 setImage:[UIImage imageNamed:self.btn1ImageName] forState:UIControlStateNormal];
}
if (btn1==0)
I don't get that part.
One easy solution would be to have two different images for a selected and un-selected state.
btn1.selected = YES, will automatically choose the selected button image.
btn1.selected = NO, will automaticall choose the un-selected button image.

Custom UIButton in UIscrollview

I am using xcode 4.6 to develop an app. Here i want to add UIButton programmatically to UIscrollview. This is the code i follow.
UIButton *bt =[[UIButton alloc]initWithFrame:frame];
bt=[UIButton buttonWithType:UIButtonTypeCustom];
[bt setTitle:#"Custom Button" forState:UIControlStateNormal];
[bt addTarget:self action:#selector(userTappedOnLink:) forControlEvents:UIControlEventTouchUpInside];
bt.backgroundColor = [UIColor grayColor];
bt.titleLabel.textColor=[UIColor blueColor];
[self.mainscrollview addSubview:bt];
[self.mainscrollview bringSubviewToFront:bt];
Now the problem is that Button gets disappeared (technically its textcolor becomes white) on click. I checked keeping UIscrollview color to red that th button was still in the view but i cant get the reason why its text color changed and how do i undo dis.
Basically I wan to create a clickable link using UIbutton.
I know uitextview approach (datadetectortype) but its of no use as i want to show different text in the label for the link and the actual link.
Note: The textcolor doesnt change back to blue and remains white only.
Thanks in advance.
Try the below code
UIButton *bt =[UIButton buttonWithType:UIButtonTypeCustom];
bt.frame = CGRectMake(50.0, 50.0, 100.0, 50.0);
[bt setTitle:#"Custom Button" forState:UIControlStateNormal];
[bt addTarget:self action:#selector(userTappedOnLink:) forControlEvents:UIControlEventTouchUpInside];
bt.backgroundColor = [UIColor grayColor];
bt.titleLabel.textColor=[UIColor blueColor];
[self.scrollTest addSubview:bt];
-(void)userTappedOnLink:(UIButton*)sender
{
NSLog(#"Test ..");
[self performSelector:#selector(changeBtnTextColor:) withObject:sender afterDelay:1.0];
}
-(void)changeBtnTextColor:(UIButton*)btn
{
btn.titleLabel.textColor=[UIColor blueColor];
}
hope it will work for you.
use below code you will get your solution
UIButton *bt =[[UIButton alloc]initWithFrame:frame];
bt=[UIButton buttonWithType:UIButtonTypeCustom];
[bt setTitle:#"Custom Button" forState:UIControlStateNormal];
[bt addTarget:self action:#selector(userTappedOnLink:) forControlEvents:UIControlEventTouchUpInside];
[bt setBackgroundColor:[UIColor grayColor]];
[bt setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[self.mainscrollview addSubview:bt];
[self.mainscrollview bringSubviewToFront:bt];
Use the below code:
[bt setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
Problem is you are set Title to titleLabel and you are changing textColor of buttonTitle color.
All the best !!!
check Button's Fram .. is it valid or not ??
and remove bt=[UIButton buttonWithType:UIButtonTypeCustom]; line from your code.

Highlight the UIButtons created Dynamically?

In my application I have created 20 buttons with in a scroll view, now problem is that I was not able to highlight the selected button.
My intention is to show the pressed button with a different look than normal. When another button is pressed the previous one should become normal:
UIButton *Abutton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
[Abutton setTag:i-1];
Abutton.frame = CGRectMake(30.0, 0+j, 40.0, 40.0);
[Abutton setTitle:#"" forState:UIControlStateNormal];
Abutton.backgroundColor = [UIColor clearColor];
[Abutton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal ];
UIImage *buttonImageNormal = [UIImage imageNamed:#"image1.png"];
UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[Abutton setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];
UIImage *buttonImagePressed = [UIImage imageNamed:#"image2.png"];
UIImage *strechableButtonImagePressed = [buttonImagePressed stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[Abutton setBackgroundImage:strechableButtonImagePressed forState:UIControlStateHighlighted];
[Abutton addTarget:self action:#selector(buttonpressed:) forControlEvents:UIControlEventTouchUpInside];
[scrollview addSubview:Abutton];
Finally I created the method for Abutton pressed as below:
-(IBAction)buttonpressed:(id)sender{
Abutton.highlighted=YES;
//.....
//.....
}
If do it like this then only the last button created dynamically gets highlighted. That's not exactly what I wanted.
I think you should replace your current code for the button pressed:
-(IBAction)buttonpressed:(id)sender{
UIButton *b = (UIButton *)sender;
b.highlighted = YES;
//.....
//.....
}
In your example you are specifically highlighting "AButton". This code highlights the button being pressed.
Solution 1:
Create an NSSet with references to all the buttons. In your buttonPressed method, call makeObjectsPerformSelector on the NSSet's buttons, setting them to the unhighlighted state.
Solution 2:
Use a UISegmentedControl. That seems like what you should be doing in this case anyway.

Resources