default selection on custom Radio Button in iphone - iphone

I want to implement radio buttons in my app
I used https://www.cocoacontrols.com/controls/radiobutton (cocoa controls Radio Buttons) .
I want that one of them should always be selected by default. how can I achive this .
My Radio button code is as follows:
RadioButton *radioButtonForDay = [[RadioButton alloc] initWithGroupId:#"first group" index:0 ];
RadioButton *radioButtonForWeek = [[RadioButton alloc] initWithGroupId:#"first group" index:1 ];
RadioButton *radioButtonForMonth = [[RadioButton alloc] initWithGroupId:#"first group" index:2 ];
radioButtonForDay.frame = CGRectMake(40,65,22,28);
radioButtonForWeek.frame = CGRectMake(130,65,22,28);
radioButtonForMonth.frame = CGRectMake(195,65,22,28);
[self.view addSubview:radioButtonForDay];
[self.view addSubview:radioButtonForWeek];
[self.view addSubview:radioButtonForMonth];
[RadioButton addObserverForGroupId:#"first group" observer:self];
RadioButton.m
`
import "RadioButton.h"
#interface RadioButton()
-(void)defaultInit;
-(void)otherButtonSelected:(id)sender;
-(void)handleButtonTap:(id)sender;
#end
#implementation RadioButton
#synthesize groupId=_groupId;
#synthesize index=_index;
static const NSUInteger kRadioButtonWidth=22;
static const NSUInteger kRadioButtonHeight=22;
static NSMutableArray *rb_instances=nil;
static NSMutableDictionary *rb_observers=nil;
pragma mark - Observer
+(void)addObserverForGroupId:(NSString*)groupId observer:(id)observer{
if(!rb_observers){
rb_observers = [[NSMutableDictionary alloc] init];
}
if ([groupId length] > 0 && observer) {
[rb_observers setObject:observer forKey:groupId];
// Make it weak reference
//[observer release];
}
}
pragma mark - Manage Instances
+(void)registerInstance:(RadioButton*)radioButton{
if(!rb_instances){
rb_instances = [[NSMutableArray alloc] init];
}
[rb_instances addObject:radioButton];
// Make it weak reference
//[radioButton release];
}
pragma mark - Class level handler
+(void)buttonSelected:(RadioButton*)radioButton{
// Notify observers
if (rb_observers) {
id observer= [rb_observers objectForKey:radioButton.groupId];
if(observer && [observer respondsToSelector:#selector(radioButtonSelectedAtIndex:inGroup:)]){
[observer radioButtonSelectedAtIndex:radioButton.index inGroup:radioButton.groupId];
}
}
// Unselect the other radio buttons
if (rb_instances) {
for (int i = 0; i < [rb_instances count]; i++) {
RadioButton *button = [rb_instances objectAtIndex:i];
if (![button isEqual:radioButton] && [button.groupId isEqualToString:radioButton.groupId]) {
[button otherButtonSelected:radioButton];
}
}
}
}
pragma mark - Object Lifecycle
-(id)initWithGroupId:(NSString*)groupId index:(NSUInteger)index {
self = [super init];
if (self) {
_groupId = groupId;
_index = index;
// _selected = selected;
[self defaultInit];
}
return self;
}
(void)dealloc
{
//[_groupId release];
// [_button release];
// [super dealloc];
}
pragma mark - Tap handling
-(void)handleButtonTap:(id)sender{
[_button setSelected:YES];
[RadioButton buttonSelected:self];
}
-(void)otherButtonSelected:(id)sender{
// Called when other radio button instance got selected
if(_button.selected){
[_button setSelected:NO];
}
}
pragma mark - RadioButton init
-(void)defaultInit{
// Setup container view
self.frame = CGRectMake(0, 0, kRadioButtonWidth, kRadioButtonHeight);
// Customize UIButton
_button = [UIButton buttonWithType:UIButtonTypeCustom];
_button.frame = CGRectMake(0, 0,kRadioButtonWidth, kRadioButtonHeight);
_button.adjustsImageWhenHighlighted = NO;
[_button setImage:[UIImage imageNamed:#"RadioButton-Unselected"] forState:UIControlStateNormal];
[_button setImage:[UIImage imageNamed:#"RadioButton-Selected"] forState:UIControlStateSelected];
[_button addTarget:self action:#selector(handleButtonTap:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:_button];
[RadioButton registerInstance:self];
}
#end
`

Initially set selected image to any of your button.
[yourBtn setImage:yourImage forState:UIControlStateNormal];
And according to your code just put handleButtonTap method in RadioButton.h
-(void)handleButtonTap:(id)sender;
and in RadioButtonViewController.m
access the button which you want to select
Its for second button (i.e. RadioButton *rb2)
for (id subView in [rb2 subviews]) {
if ([subView isKindOfClass:[UIButton class]]) {
[rb2 handleButtonTap:subView];
}
}

Try this :
for default selection
[btnR setImage:[UIImage imageNamed:#"btnCheck.png"] forState:UIControlStateNormal];
[btnG setImage:[UIImage imageNamed:#"btnUnCheck.png"] forState:UIControlStateNormal];
[btnB setImage:[UIImage imageNamed:#"btnUnCheck.png"] forState:UIControlStateNormal];
and when you go to next view just check condition....
UIImage* selectedImg=[UIImage imageNamed:#"btnCheck.png"]; //btnCheck.png your image name
if (btnR.imageView.image == selectedImg || btnG.imageView.image == selectedImg || btnB.imageView.image == selectedImg)
{
//One of them is selected
}
else {
NSLog(#"Please Select At least One Color" );
}

Related

How to compare 2 button title using index or tag value

Here my application i having set of button 12 buttons,button titles are hidden by default.Button titles are shown when it is clikced ,
-(IBAction)buttonAction:(id)sender
{
UIButton *button = (UIButton *)sender;
int index = button.tag;
[self showing:index]; //now, this method accepts a parameter.
}
-(void)showing:(NSInteger)index
{
UIButton* btn = nil;
index = index - 1;
NSArray* subViewArray = [self.view subviews];
NSInteger i = 0;
for (UIView *view in subViewArray)
{
if ([view isKindOfClass:[UIButton class]])
{
btn = (UIButton*) view;
if(btn.tag >= 1 && btn.tag <= 16)
{
NSString* text;
UIButton *prevButton = (UIButton*) [self.view viewWithTag:previousButtonTag];
if (i == index) {
if ([btn.titleLabel.text isEqualToString:prevButton.titleLabel.text])
{
}
else
{
text=#"";
}
text = [texts objectAtIndex:i]; //put the array that you are using
}
else {
text = #"";
}
i++;
[btn setTitle:text forState:UIControlStateNormal];
}
}// end of IF
} //end of FOR
}
1.I want to compare two button title values to check whether it is equal or not.Im facing the problem ,
2.Only press button title only visible,when i click other button previous title is hided,I want to enable two button title on click and wen it is wrong it should be hided.Please suggest me the How to solve this issue,Please do the needfully
Do some changes with this code , i just try to understand your requirement and add logic for display title of previous button and current button title..
-(void) showing:(NSInteger)index
{
UIButton* btn = nil;
index = index - 1;
NSArray* subViewArray = [self.view subviews];
NSInteger i = 0;
UIButton *btnCurTemp = (UIButton *)[self.view viewWithTag:index];
for (UIView *view in subViewArray)
{
if ([view isKindOfClass:[UIButton class]])
{
btn = (UIButton*) view;
NSString* text;
if (i == index) {
text = [self.textArray objectAtIndex:i]; //put the array that you are using
[btnCurTemp setTitle:text forState:UIControlStateNormal];
UIButton *btnPrevTemp = (UIButton *)[self.view viewWithTag:self.prevButtonTag];
if ([btnCurTemp.titleLabel.text isEqualToString:btnPrevTemp.titleLabel.text]) {
/// visible your both button title..
}
else {
//// hide button title..
}
self.previousButtonTag = i; //make a class variable
}else {
text = #"";
}
i++;
}
}
}
Change your showing like:
-(void) showing:(NSInteger)index
{
UIButton *btn = (UIButton*) [self.view viewWithTag:index];
NSString *text = [self.textArray objectAtIndex:index]; //put the array that you are using
[btn setTitle:text forState:UIControlStateNormal];
if (self.previousButtonTag != -1)
{
UIButton *prevButton = (UIButton*) [self.view viewWithTag:previousButtonTag];
if ([btn.titleLabel.text isEqualToString:prevButton.titleLabel.text])
{
}
else
{
//hide the prevButton
[prevButton setTitle:#"" forState:UIControlStateNormal];
}
}
self.previousButtonTag = index; //make a class variable
}
IButton *btn = (UIButton*) [self.view viewWithTag:index]; will give you the currently clicked button. UIButton *prevButton = (UIButton*) [self.view viewWithTag:previousButtonTag]; give you the previously clicked button. As per your need you can check the titles in the if condition, if they are equal do your stuff there, if not equal then hiding the previous button title.
You need to initialize the previous button tag to -1 in your viewDidLoad
Why don't you simply compare the array strings values using the button tags as the index -
NSString * firstString = [self.textArray objectAtIndex:btn.tag];
NSString * secondString = [self.textArray objectAtIndex:prevButton.tag];
if([firstString isEquleToString:secondString]){
}else{
}

clear uibutton title and reset again

I Follow the comment and try to fix my problem,but still not working.
when i run the test demo on the simulator,i get this:
run the demo project view
and i click the test2, i want to change button title before clear the button title, but i
get this :
after i click test2 button
i can not clear the button title when click another button.
anyone can help ??
Here is my code
-(void)addbutton
{
for (int i=0; i<3; i++)
{
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake((i*100), 0, 100, 100)];
button.titleLabel.text = #"";
[button setTag:i];
[button setTitle:[self.demoDataArray objectAtIndex:i] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.backgroundColor = [UIColor clearColor];
[button addTarget:self action:#selector(setButtonTitle:) forControlEvents:UIControlEventTouchUpInside];
[self.demoView addSubview:button];
}
}
-(IBAction)setButtonTitle:(id)sender
{
if ([sender tag] == 0)
{
self.demoDataArray = [[NSArray alloc] initWithObjects:#"test5", #"test6", #"test7", #"test8", nil];
[self addbutton];
}
else if([sender tag] == 1)
{
self.demoDataArray = [[NSArray alloc] initWithObjects:#"test9", #"test10", #"test11", #"test12", nil];
[self addbutton];
}
else if([sender tag] == 3)
{
self.demoDataArray = [[NSArray alloc]initWithObjects:#"test13", #"test14", #"test15", #"test16", nil];
[self addbutton];
}
}
Every time any button is pressed, you instantiate new buttons and add them on top of the other ones. You probably want to just update the existing buttons. Try this for your -addButton method instead:
-(void)addbutton
{
for (int i=0;i<3;i++)
{
NSInteger tag = i+1;
UIButton *button = (UIButton *)[self.view viewWithTag:tag];
if (!button)
{
button = [[UIButton alloc] initWithFrame:CGRectMake((i*100), 0, 100, 100)];
[button addTarget:self action:#selector(setButtonTitle:) forControlEvents:UIControlEventTouchUpInside];
[button setTag:tag];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.backgroundColor = [UIColor clearColor];
[self.demoView addSubview:button];
}
button.titleLabel.text = #""; // Not actually sure you need this...
NSString *titleText = nil;
if (i < self.demoDataArray.count)
titleText = [self.demoDataArray objectAtIndex:i];
[button setTitle:titleText forState:UIControlStateNormal];
}
}
Now the button is instantiated, given a target and action, tagged, and added into the button hierarchy only when it doesn't already exist. Every time a button is tapped after that, only the titles will be updated.
Also, very important:: in order for -viewWithTag: to work, you have to use a tag for your buttons that is not equal to 0, the default tag - otherwise the button's superview will be returned. This means you'll need to make the following changes in your button handler, which already had a bug with checking the tags (checking against 3 rather than 2). Increment the tags to start at 1 and end with 3 like so:
-(IBAction)setButtonTitle:(id)sender
{
if ([sender tag] == 1)
{
self.demoDataArray = [[NSArray alloc] initWithObjects:#"test5",#"test6",#"test7",#"test8", nil];
[self addbutton];
}
else if([sender tag] == 2)
{
self.demoDataArray = [[NSArray alloc] initWithObjects:#"test9",#"test10",#"test11",#"test12", nil];
[self addbutton];
}
else if([sender tag] == 3)
{
self.demoDataArray = [[NSArray alloc]initWithObjects:#"test13",#"test14",#"test15",#"test16", nil];
[self addbutton];
}
}
That method could use some cleanup as well to eliminate duplicated code and it's probably more appropriate to use a switch statement here anyways. But that's neither here nor there.
OK, this should probably get you up and running. I didn't test or compile this so if you do have some problem with the compiler that you're not able to work through on your own please let me know and I'll see if I can spot the issue.
try this
- (IBAction)firstbtn:(UIButton *)sender {
[secondbtn setTitle:#"" forState:UIControlStateNormal];
}

Dynamic assignment of random images as button's background separately

-(void)setButtons_AsPerTheMatrixSelection
{
for(UIView *subview in [viewWithButtons subviews])
{
if ([subview isKindOfClass:[UIButton class]])
{
[subview removeFromSuperview];
}
}
viewWithButtons = [[UIView alloc] init];
width = 48;
height = 48;
pw = 49;
ph = 49;
arrButton = [[NSMutableArray alloc] init];
UIImage *imgDefaultBG = [UIImage imageNamed:#"bg.jpg"];
viewWithButtons.frame = CGRectMake(50, 40, 200, 260);
ch = 4;
cv = 4;
for ( i = 0 ; i < cv ; ++i )
{
for ( j = 0 ; j < ch ; ++j )
{
btnMatrix = [[[UIButton alloc] initWithFrame:CGRectMake(10+pw*j, 51+ph*i, width, height)] autorelease];
btnMatrix.tag = i*ch+j;
btnMatrix.userInteractionEnabled = TRUE;
bulImageStatus = FALSE;
[btnMatrix addTarget:self action:#selector(changeImage:) forControlEvents:UIControlEventTouchDown];
[btnMatrix setBackgroundImage:imgDefaultBG forState:UIControlStateNormal];
[viewWithButtons addSubview:btnMatrix];
[arrButton addObject:btnMatrix];
}
}
NSLog(#"arrButton object count is:--> %d",[arrButton count]);
[self.view addSubview:viewWithButtons];
}
-(void)AddImageToArray
{
arr_FirstSet = [[NSMutableArray alloc] init];
NSString *strImageName;
if(appDelegate.intCategoryBtnTag == 0)
{
for (intimg = 1; intimg <= 28; intimg++)
{
strImageName = [NSString stringWithFormat:#"%d_1.png",intimg];
NSLog(#"strImageName is :--> %#",strImageName);
[arr_FirstSet addObject:strImageName];
}
NSLog(#"arr_FirstSet objects are...%#",arr_FirstSet);
}
}
-(void)changeImage:(id)sender
{
UIImage *img;
NSString *strImageName;
strImageName = [arr_FirstSet objectAtIndex:arc4random() % [arr_FirstSet count]/2];
NSLog(#"btnMatrix is:--> %#",strImageName);
img = [UIImage imageNamed:strImageName];
//[btnMatrix setImage:img forState:UIControlEventTouchDown];
NSLog(#"sender detail is:--> %#",sender);
[sender setBackgroundImage:img forState:UIControlStateHighlighted];
}
This is my code to set the dynamic buttons in "setButtons_AsPerTheMatrixSelection" method,
"AddImageToArray" method is used to add images from bundle to NSMutableArray (arr_FirstSet) one by one.
"changeImage" method is used to set the background of particular button.
I am able to set the images as background to the buttons randomly,
But the main problem is that i have to set fixed dynamic image to particular button.
right now on each click of particular button i am getting changed random image when i press it once, twice, thrice etc...
I have to set any particular image which is generated randomly in the "changeImage" to single button & rest to the other buttons single-single.
Then i have to check if two buttons have same background then these two buttons will be removed from the matrix.
Please guide me for the mistake i am doing & help me.
//Please replace this method
-(void)changeImage:(UIButton *)sender
{
UIImage *img;
NSString *strImageName;
strImageName = [arr_FirstSet objectAtIndex:arc4random() % [arr_FirstSet count]/2];
img = [UIImage imageNamed:strImageName];
//for the first time sender.imageView.image property will be null then only we set image to the button.
//For second click this condition fails and does not set the other image.
if(!sender.imageView.image)
{
[sender setImage:img forState:UIControlStateHighlighted];
[sender setImage:img forState:UIControlStateSelected];
}
// Calling a method to check if two images of buttons are same.
[self checkIfTwoImagesAreSame:sender];
}
//And Add this method
- (void)checkIfTwoImagesAreSameImageMaching:(UIButton *)sender
{
for(UIView *subview in [viewWithButtons subviews])
{
if ([subview isKindOfClass:[UIButton class]])
{
UIButton *btn = (UIButton *)subview;
// This condition is comparing clicked button image with all the buttons images of the viewWithButtons view if it isEqual:
if(sender.imageView.image && btn.imageView.image && [sender.imageView.image isEqual:btn.imageView.image])
{
// this is checking if the clicked button is not comparing with itself
if(btn.tag != sender.tag)
{
[btn removeFromSuperview];
[sender removeFromSuperview];
// OR
// btn.selected = YES;
// sender.selected = YES;
// OR
// btn.hidden = YES;
// sender.hidden = YES;
}
}
}
}
}

how to set multiple buttons in UIScrollView?

how to set multiple buttons in UIScrollView and also how to set clicked action for particular button index?
UIScrollView *view = ..;
UIButton *button1 = ... ;
button1.tag = 1;
UIButton *button2 = ... ;
button1.tag = 2;
UIButton *button3 = ... ;
button1.tag = 3;
[view addSubview:button1];
[view addSubview:button2];
[view addSubview:button3];
In IBAction method check button tag to identify clicked button.
you can call this(initScrollView) method on viewDidLoad
- (void)viewDidLoad {
arrayScrollViewImages = [[NSArray alloc] initWithObjects:
[[MyKeyValuePair alloc] initWithKey:#"imagename1" withValue:#"imagename1.png"],
[[MyKeyValuePair alloc] initWithKey:#"imagename2" withValue:#"imagename2.png"],nil];
[self initScrollView];
}
here arrayScrollViewImages is NSArray
- (void) initScrollView
{
int width = 10;
for (int index = 0; index < [arrayScrollViewImages count]; index++) {
MyKeyValuePair *pair = [arrayScrollViewImages objectAtIndex:index];
UIImage *image = [UIImage imageNamed:pair.value];
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(width, 2, 34, 34)];
[button setBackgroundImage:image forState:UIControlStateNormal];
[button setTag:index];
[button addTarget:self action:#selector(scrollViewButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
if (index == 0) {
[button setBackgroundColor:[UIColor colorWithRed:0.59 green:0.38 blue:0.21 alpha:1.00]];
}
[scrollView addSubview:button];
width += 45;
}
scrollView.contentSize = CGSizeMake(width, 48);
scrollView.contentOffset = CGPointMake(0, 0);
}
- (void) scrollViewButtonTapped:(id)sender {
for (UIButton *b in scrollView.subviews) {
if ([b isKindOfClass:[UIButton class]]) {
[b setBackgroundColor:[UIColor clearColor]];
}
}
UIButton *button = (UIButton *) sender;
[button setBackgroundColor:[UIColor colorWithRed:0.59 green:0.38 blue:0.21 alpha:1.00]];
MyKeyValuePair *pair = [arrayScrollViewImages objectAtIndex:button.tag];
labelEspecialidad.text = pair.key;
}
here MyKeyValuePair is a one class
*MyKeyValuePair.h*
#interface MyKeyValuePair : NSObject {
NSString *key;
NSString *value;
}
// Properties
#property (nonatomic, retain) NSString *key;
#property (nonatomic, retain) NSString *value;
#end
MyKeyValuePair.m
#implementation MyKeyValuePair
#synthesize key, value;
- (id) initWithKey: (NSString *) _key withValue: (NSString *) _value {
if (self = [super init]) {
self.key = _key;
self.value = _value;
}
return self;
}
- (void) dealloc {
[super dealloc];
[self.key release];
[self.value release];
}
#end
Using XCode Interface Builder
Add buttons (select and drag&drop them from side objects panel)
Create IBAction for every button (in owner class .h and implement in .m)
Link buttons to actions via right mouse click&drag
See some video tutorials on youtube, such as
http://www.youtube.com/watch?v=WgAAvRQBrPc
http://www.youtube.com/watch?v=uAdmetwz7sc
http://www.youtube.com/watch?v=vixD-N6cbDY
and read Developer Guide
http://www.switchonthecode.com/tutorials/creating-your-first-iphone-application-with-interface-builder
http://developer.apple.com/library/ios/#documentation/IDEs/Conceptual/Xcode4TransitionGuide/InterfaceBuilder/InterfaceBuilder.html
You can use an array of buttons for that purpose. Assign a unique tag id to each button, and programmatically spread the buttons along the UIScrollView. Have the UIScrollView listen to the Touch Up Inside event, where you can then determine which button has been clicked by the unique tag ID.

how do I only allow one selected button at a time? / make button know if i click somewhere else

how do i make these buttons so that only one can be used at a time? Im not getting any errors right now when i run btw. Im just looking for a solution to my challenge. Thanks for any help
they are generated in a for loop like this:
for (int l=0; l<list.length; l++) {
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton setTag:l];
CGRect buttonRect = CGRectMake(11+charact*20, -40 + line*50, 18, 21);
aButton.frame = buttonRect;
[aButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[aButton setTitle:#" " forState:UIControlStateNormal];
[gameScroll addSubview:aButton];
}
And then the action for when a button is clicked is:
- (void) buttonClicked:(UIButton *)sender {
int tag = sender.tag;
if (sender.selected == TRUE) {
[sender setSelected:FALSE];
[sender setBackgroundColor:[UIColor clearColor]];
}
else if (sender.selected == FALSE) {
[sender setSelected:TRUE];
[sender setBackgroundColor:[UIColor redColor]];
}
}
right now everything works but i want it to know if theres already a button selected and deselect that other button, or else to automatically deselect any time the user clicks outside of the range of that button
thanks in advance
I would suggest to put all ur buttons to Array in your button initialisation
NSMutableArray* buttons = [NSMutableArray arrayWithCapacity: list.length];
for (int l=0; l<list.length; l++) {
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton setTag:l];
CGRect buttonRect = CGRectMake(11+charact*20, -40 + line*50, 18, 21);
aButton.frame = buttonRect;
[aButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[aButton setTitle:#" " forState:UIControlStateNormal];
[gameScroll addSubview:aButton];
[buttons addObject: aButton];
}
and every time buttonClicked triggered, then do your logic:
for (UIButton* button in buttons)
{
if (button != sender)
{
[button setSelected: FALSE];
[button setBackgroundColor:[UIColor redColor]];
}
}
int tag = sender.tag;
if (sender.selected == TRUE) {
[sender setSelected:FALSE];
[sender setBackgroundColor:[UIColor clearColor]];
}
else if (sender.selected == FALSE) {
[sender setSelected:TRUE];
[sender setBackgroundColor:[UIColor redColor]];
}
hope helps :)
You can store currently selected button in a separate variable and deselect it in buttonClicked: method:
- (void) buttonClicked:(UIButton *)sender {
int tag = sender.tag;
currentButton.selected = NO;
if (currentButton != sender){
currentButton = sender;
currentButton.selected = YES;
}
else{
currentButton = nil;
}
}
Also you can specify background colour for each state in button itself so you actually don't need to change it each time manually
If you also want to deselect your button when user just touches the screen you can implement touchesEnded:withEvent: in your view controller and reset currentButton in it (that method will get called if no other control intercept the touch event - so it may not be sufficient in all cases)
- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event{
currentButton.selected = NO;
currentButton = nil;
}