automatically set selected UIbutton highlighted in XCode? - ios

I am displaying a NSMutableArray items in UITableViewCell acting like gridview.There are custom UIbuttons in a cell.Now when a user click on one button I want it to get highlighted.But when I am doing it what is happening is when I click on a button its colour changes to red .But when i click on the next button its colour is also changed to red but the prevoius buttons colour is also red.I want the prevoius button to remain unhighlighted and the present button to be highlighted .How can I do it?
This is my code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
CGRect rect = CGRectMake(18+80*j, yy,57, 40);
UIButton *button=[[UIButton alloc] initWithFrame:rect];
[button setFrame:rect];
[button setContentMode:UIViewContentModeCenter];
NSString *settitle=[NSString stringWithFormat:#"%#",item.title];
[button setTitle:settitle forState:UIControlStateNormal];
NSString *tagValue = [NSString stringWithFormat:#"%d%d", indexPath.section+1, i];
button.tag = [tagValue intValue];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button addTarget:self action:#selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
[hlcell.contentView addSubview:button];
[button release];
}
-(IBAction)buttonPressed:(id)sender {
int tagId = [sender tag];
int divNum = 0;
if(tagId<100)
divNum=10;
else
divNum=100;
int section = [sender tag]/divNum;
section -=1;
int itemId = [sender tag]%divNum;
UIButton *button = (UIButton *)sender;
if(button.enabled==true)
{
button.backgroundColor=[UIColor redColor];
}
NSLog(#"…section = %d, item = %d", section, itemId);
NSMutableArray *sectionItems = [sections objectAtIndex:section];
Item *item = [sectionItems objectAtIndex:itemId];
NSLog(#"..item pressed…..%#, %#", item.title, item.link);
}
How can I do it?

one way to do it, is to keep an IBCollection reference for all your buttons in your header file (hook up all your buttons in Interface builder to this IBOutletCollection):
#property (nonatomic, retain) IBOutletCollection(UIButton) NSArray *allOfMyButtons;
and in your buttonPressed method make the background color red only if its the currently pressed button AND that button is enabled (all others turn back to black or whatever the initial color was):
-(IBAction)buttonPressed:(id)sender {
[self.allOfMyButtons enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UIButton *button = (UIButton *)obj;
if (button != sender && button.enabled) {
[button setBackgroundColor:[UIColor redColor]];
} else {
[button setBackgroundColor:[UIColor blackColor]];
}
}];
}

Related

How to change a image when when we click a button?

I'm working with radio buttons, for this i'm writing code like this.
float x = 40;
float y = 0;
for (int i=0; i<self.radioBtnTagArr.count; i++) {
self.radioButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.radioButton.frame = CGRectMake(x, y+35, 35.0, 35.0);
[self.radioButton setImage:[UIImage imageNamed:#"radio_empty.png"] forState:UIControlStateNormal];
[self.radioButton addTarget:self action:#selector(radioBtnMethod:) forControlEvents:UIControlEventTouchUpInside];
[self.scrollView addSubview:self.radioButton];
self.radioButton.tag = [[self.radioBtnTagArr objectAtIndex:i] intValue];
y = y+70;
}
This "self.radioBtnTagArr" comes from server (tags comes from server), based on that count i want to create radio buttons and i'm assigning tag that tags to radio buttons.
- (void) radioBtnMethod:(UIButton *)sender {
for (int i=0; i<self.radioBtnTagArr.count; i++) {
if (sender.tag == [[self.radioBtnTagArr objectAtIndex:i] intValue]) {
[self.radioButton setImage:[UIImage imageNamed:#"radio.png"] forState:UIControlStateSelected];
[self.radioButton setSelected:YES];
}
}
}
Now the problem is when i click first radio button the last radio button was selected like this below image...
I want only when we click first button first button state selected, if we click second button second button state selected like this...
do like create another one array for save the UIbutton, for e.g
Step-1
#property (nonatomic, strong) NSMutableArray *buttonArray;
step-2
add the all buttons to buttonArray
// allocate the memory for your array
buttonArray = [NSMutableArray array];
for (int i=0; i<self.radioBtnTagArr.count; i++) {
// create instance value of UIButton
UIButton *radioButton = [UIButton buttonWithType:UIButtonTypeCustom];
radioButton.frame = CGRectMake(x, y+35, 35.0, 35.0);
[radioButton setImage:[UIImage imageNamed:#"radio_empty.png"] forState:UIControlStateNormal];
[radioButton addTarget:self action:#selector(radioBtnMethod:) forControlEvents:UIControlEventTouchUpInside];
[self.scrollView addSubview:self.radioButton];
y = y+70;
// add the object to array
[buttonArray addObject:radioButton];
}
step-3
inside the target
- (void) radioBtnMethod:(UIButton *)sender {
// reset the previous selection
for (UIButton *getradioButton in buttonArray) {
[getradioButton setImage:[UIImage imageNamed:#"radio_empty.png"] forState:UIControlStateNormal];
}
// set the current selection
[sender setImage:[UIImage imageNamed:#"radio.png"] forState:UIControlStateNormal];
}

Programmatically Click 10 UIButtons one after another in UIScrollView

I am developing one control where 10 UIButtons are added in UIScrollView. Now I have a requirement to click every Button one after another after some delay. can you all guide me how to do that?
here is the code what I have done.
in viewcontroller.h file
#property (weak) IBOutlet UIScrollView *mapScrollView;
#property (strong) UIButton *addContactIcon;
in viewcontroller.m file
// Set up ScrollView with UIButtons
NSUInteger xPosition = 1;
NSUInteger countIndex = 0;
for (ContactModule *sortedContacts in _distanceList) {
_addContactIcon = [[UIButton alloc] initWithFrame:CGRectMake(xPosition, 7, 30, 30)];
_addContactIcon.tag = countIndex;
[_addContactIcon addTarget:self action:#selector(mapsScrollButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
_addContactIcon.layer.cornerRadius = 2.0;
_addContactIcon.clipsToBounds = YES;
[_addContactIcon setBackgroundImage:[UIImage imageWithContentsOfFile:dataPath] forState:UIControlStateNormal];
[_addContactIcon setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[_mapScrollView addSubview:_addContactIcon];
xPosition += _addContactIcon.frame.size.width + 2;
countIndex = countIndex + 1;
}
_mapScrollView.contentSize = CGSizeMake(30 * _distanceList.count + 34, 40);
[_mapScrollView setShowsHorizontalScrollIndicator:NO];
Here is the Button Click Method For Every Button:
- (void)mapsScrollButtonClicked:(UIButton *)clickButton {
// Set Annotation Callout
[_mapsView selectAnnotation:[_mapsView.annotations objectAtIndex:clickButton.tag] animated:YES];
}
Now the requirement is I want to call Action Method for Every UIButtons in UIScrollview. for that I am doing something wrong below. help me with that:
for(NSUInteger count=0; count<[_distanceList count];count++) {
[UIView animateWithDuration:0.4
delay:0.8
options:0
animations:^{
[_addContactIcon sendActionsForControlEvents:UIControlEventTouchUpInside];
} completion:nil];
}
Hi you could do soemthing like below to click all the UIButtons on your view.
UIButton *button;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIButton *buttonMaster;
buttonMaster = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[buttonMaster addTarget:self
action:#selector(masterButtonTapped:)
forControlEvents:UIControlEventTouchUpInside];
[buttonMaster setTitle:#"Show View" forState:UIControlStateNormal];
buttonMaster.frame = CGRectMake(80.0, y, 160.0, 40.0);
buttonMaster.tag = 100;
[self.view addSubview:buttonMaster];
y = 60;
for (int x=0; x<=10; x++)
{
button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(button1:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:#"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, y, 160.0, 30.0);
button.tag = x;
//[paintView addSubview:button];
[self.view addSubview:button];
y = y + 70;
}
[buttonMaster sendActionsForControlEvents:UIControlEventTouchUpInside];
if ([[self.view viewWithTag:0] isKindOfClass:[UIButton class]]) {
//UIButton *button = (UIButton *) view;
// do something funky with button
UIButton *myBtns = (UIButton *)[self.view viewWithTag:0];
NSLog(#" button tapped is %ld", myBtns.tag);
[myBtns sendActionsForControlEvents:UIControlEventTouchUpInside];
[myBtns setBackgroundColor:[UIColor greenColor]];
} else {
// do something funky with view
NSLog(#"do nothing ");
}
}
- (void)listSubviewsOfView:(UIView *)view {
// Get the subviews of the view
NSArray *subviews = [view subviews];
// Return if there are no subviews
//if ([subviews count] == 0) return; // COUNT CHECK LINE
for (UIView *subview in subviews) {
UIButton *myBtns = (UIButton *)[self.view viewWithTag:subview.tag];
//UIButton *myBtns = (UIButton *)[self.view viewWithTag:0];
if(myBtns.tag == 100 ){
NSLog(#"Master Button tag :- Dont do anything ");
}else
{
//[myBtns sendActionsForControlEvents:UIControlEventTouchUpInside];
NSLog(#"tags are %ld ", myBtns.tag);
}
// List the subviews of subview
//[self listSubviewsOfView:subview];
}
}
-(void) clickAllButtons{
for (int i = 0; i<=10; i++) {
UIButton *myBtns = (UIButton *)[self.view viewWithTag:i];
[myBtns sendActionsForControlEvents:UIControlEventTouchUpInside];
}
}
- (IBAction)masterButtonTapped:(UIButton*)sender{
//[self listSubviewsOfView:self.view];
// [self clickAllButtons];
}
- (IBAction)button1:(UIButton*)sender{
NSLog(#"test");
//NSLog(#"Button clicked %ld", tag);
}

how to set 1 checkbox always selected when all other check box is not selected

how do I set 1 checkbox always checked when all other check boxes are not selected
the below code I used is perfectly fine but Iam unable to set 1 checkbox selected
int x=0;
checkbox1 = [[UIButton alloc] initWithFrame:CGRectMake(350,600+x,50,50)];
[checkbox1 setBackgroundImage:[UIImage imageNamed:#"checkboxunchecked.png"]forState:UIControlStateNormal];
[checkbox1 setBackgroundImage:[UIImage imageNamed:#"checked.png"]forState:UIControlStateSelected];
[checkbox1 setBackgroundImage:[UIImage imageNamed:#"checked.png"]forState:UIControlStateHighlighted];
checkbox1.adjustsImageWhenHighlighted=NO;
checkbox1.tag=1;
[checkbox1 addTarget:self action:#selector(checkboxSelectedMethod:) forControlEvents:UIControlEventTouchUpInside ];
[self.view addSubview:checkbox1];
x+=checkbox1.frame.size.width*1.5;
checkbox2 = [[UIButton alloc] initWithFrame:CGRectMake(350,600+x,50,50)];
[checkbox2 setBackgroundImage:[UIImage imageNamed:#"checkboxunchecked.png"]forState:UIControlStateNormal];
[checkbox2 setBackgroundImage:[UIImage imageNamed:#"checked.png"]forState:UIControlStateSelected];
[checkbox2 setBackgroundImage:[UIImage imageNamed:#"checked.png"]forState:UIControlStateHighlighted];
checkbox2.adjustsImageWhenHighlighted=NO;
checkbox2.tag=1;
[checkbox2 addTarget:self action:#selector(checkboxSelectedMethod:) forControlEvents:UIControlEventTouchUpInside ];
[self.view addSubview:checkbox2];
x+=checkbox2.frame.size.width*1.5;
similarly 2 more buttons are there total there are 4 buttons, first button should get selected if other 3 are not selected
-(void)checkboxSelectedMethod:(id)sender
{
UIButton *btn = (UIButton *) sender;
if([checkbox1 isSelected])
{
[btn setSelected:NO];
}
else{
[btn setSelected:YES];
}
if([checkbox2 isSelected])
{
[btn setSelected:NO];
}
else{
[btn setSelected:YES];
}
}
It will be much easier if you use an array to store your buttons rather than discrete variables -
#property (strong,nonatomic) NSMutableArray *checkboxes;
#property (strong,nonatomic) UIImage *checkedImage;
#property (strong,nonatomic) UIImage *checkedImage;
#property (strong,nonatomic) NSMutableIndexSet *selectedSet;
int x=0;
self.uncheckedImage=[UIImage imageNamed:#"checkboxunchecked.png"];
self.checkedImage=[UIImage imageNamed:#"checked.png"];
self.selectedSet=[NSMutableIndexSet new]; //Indexset to store selected buttons
self.checkboxes=[NSMutableArray new];
for (int i=0i;i<3;i++) {
UIButton *checkbox = [[UIButton alloc] initWithFrame:CGRectMake(350,600+x,50,50)];
[checkbox setBackgroundImage:uncheckedImage forState:UIControlStateNormal];
[checkbox setBackgroundImage:checkedImage forState:UIControlStateSelected];
[checkbox setBackgroundImage:uncheckedImage forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted=NO;
checkbox.tag=i;
[checkbox addTarget:self action:#selector(checkboxSelectedMethod:) forControlEvents:UIControlEventTouchUpInside ];
[self.view addSubview:checkbox];
[self.checkboxes addObject:checkbox];
x+=checkbox.frame.size.width*1.5;
}
Now you can check if sender is in the index set (selected) and remove it if the count in the set is >1 (more than one box selected). If not in the set then it is not selected, so select it and add it to the set
-(void)checkboxSelectedMethod:(id)sender
{
UIButton *btn = (UIButton *) sender;
NSInteger buttonIndex=btn.tag;
if ([self.selectedSet containsIndex:buttonIndex]) {
if (self.selectedSet.count > 1) {
[self.selectedSet removeIndex:buttonIndex];
[btn setSelected:NO];
}
} else {
[btn setSelected:YES];
[self.selectedSet addIndex:buttonIndex];
}
}

How to make segmented control like this

Today I'm creating a custom segmented control. The appearance of the control as follow:
I tried two methods:
- (void)setBackgroundImage:(UIImage *)backgroundImage
forState:(UIControlState)state
barMetrics:(UIBarMetrics)barMetrics
- (void)setDividerImage:(UIImage *)dividerImage
forLeftSegmentState:(UIControlState)leftState
rightSegmentState:(UIControlState)rightState
barMetrics:(UIBarMetrics)barMetrics
However, here is the result I got:
I extracted the border image and the divider line (vertical line) from the design, but the result looks bad. Please help me if you have any idea.
I have always found it too much work to customize the UISegmentedControl and it is not really fully customizable.
I suggest you create yourself a custom UIView inheriting 3 buttons. They are fully customizable and fully controllable:
#define BASE_TAG 123
NSArray *titles = [NSArray arrayWithObjects:#"MAP", #"LOCATIONS", #"BUS", nil];
double y = 0.0;
double x = 0.0;
double width = (frame.size.width / [titles count]);
double height = frame.size.height;
for (int i = 0; i < [titles count]; i++)
{
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake(x, y, width, height)];
[button.titleLabel setTextAlignment:NSTextAlignmentCenter];
[button setBackgroundColor:[UIColor clearColor]];
[button setTag:(BASE_TAG + ([titles count] - i - 1))];
[button addTarget:self action:#selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
[_buttons addObject:button];
x += width;
}
This is your button action. Here the button clicked will be selected and all others unselected:
- (void)buttonAction:(id)sender
{
UIButton *button = (UIButton *)sender;
NSInteger index = 0;
for (UIButton *btn in self.subviews)
{
if (btn == button)
{
index = (btn.tag - BASE_TAG);
[btn setBackgroundColor:[UIColor colorFromHexString:#"#5ac8f5" alpha:1.0]];
[btn setSelected:YES];
}
else
{
[btn setBackgroundColor:[UIColor clearColor]];
[btn setSelected:NO];
}
}
/* Trigger a delegate here if you like
if ([_delegate respondsToSelector:#selector(didSelectedIndex:)])
{
[_delegate didSelectedIndex:index];
}
*/
}
This lets you pre set a selected index:
- (void)setSelectedIndex:(NSInteger)index
{
for (UIButton *button in self.subviews)
{
if (button.tag == (BASE_TAG + index))
{
[button setBackgroundColor:[UIColor colorFromHexString:#"#5ac8f5" alpha:1.0]];
[button setSelected:YES];
}
else
{
[button setBackgroundColor:[UIColor clearColor]];
[button setSelected:NO];
}
}
}
This is just a suggestion code I pulled from an old project. You will have to customize it for your needs.
Here is a very good article how to do custom segmented control.
Looks like you have tried similar approach but you have messed up something with images (probably you misunderstand the API so this article should do the job for you).

How to select all buttons when we select last button in ios

Iam new to IOS programming,i have one doubt explained below:
I have 10 buttons as stars in the view,
If i click 10th button i need to show all buttons as selected.
If i click 5th button i need to show 5 buttons as selected.
I need this functionality to give rating in my ios app.
Please can anyone suggest me the solution for my question.
Thanks in advance
If I have to do this then I will give this button row an incremented tag from 1 to 10, then if someone press the 5 button i will get its tag and using loop change the button images from 1 to 5 getting the object of button using tag.
like you have selector for all button
-(void)userRatingAction:(id)sender {
UIButton* button = (UIButton*)sender;
for(int index = 1; index <= button.tag; index++) {
UIButton* ratingButton = (UIButton*)[self.view viewWithTag:index];
// set the button image here
}
}
I think you can find your answer with the help of below link http://try.sencha.com/touch/2.2.0/demos/Ext.List.select/
Use of Tag property can solve the problem.
Assign tag to all the UIButtons you have starting from 1-10. Create a common IBAction and on action..
-(IBAction)btnAction:(id)sender{
UIButton *selectedBtn=(UIButton *)sender;
//First Reset all the selection
for(UIButton *btn in self.view.subviews){
if([btn isKindOfClass:[UIButton class]]){
if(btn.tag>=1 && btn.tag<=10){
btn.selected=NO;
}
}
}
//Now Select
for(UIButton *btn in self.view.subviews){
if([btn isKindOfClass:[UIButton class]]){
if(btn.tag>=1 && btn.tag<=selectedBtn.tag){
btn.selected=YES;
}
}
}
}
Thats it.
Cheers.
To draw star buttons -
make imgArr global nsmutable array to store button objects
imgArr = [[NSMutableArray alloc ]init];
float leftMargin = 10;
float topMargin = 50;
for (int i=0; i<10; i++) {
UIButton *starBtn = [[UIButton alloc]initWithFrame:CGRectMake(leftMargin, topMargin, 25, 25)];
[starBtn setBackgroundColor:[UIColor clearColor]];
[starBtn setImage:[UIImage imageNamed:#"star_empty.png"] forState:UIControlStateNormal];
[starBtn setTag:i+1];
[starBtn setTitle:[NSString stringWithFormat:#"%d",i] forState:UIControlStateNormal];
[starBtn addTarget:self action:#selector(starBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:starBtn];
[imgArr addObject:starBtn];
leftMargin += 35;
}
-(void)starBtnClicked:(UIButton *)tempBtn{
NSLog(#"TEMP BTN CLICKED :: %#",tempBtn.titleLabel.text);
for (int i=0; i<imgArr.count; i++) {
UIButton *btn = (UIButton *)[imgArr objectAtIndex:i];
if(i < tempBtn.tag){
[btn setImage:[UIImage imageNamed:#"star_full.png"] forState:UIControlStateNormal];
}else{
[btn setImage:[UIImage imageNamed:#"star_empty.png"] forState:UIControlStateNormal];
}
}
}
to do so follow these steps.
Step 1 - From xib set tag of all buttons sequentially in incremented order. (e.g. 101, 102, 103, 104, 105, 106, 107, 108, 109, 110)
Step 2 - Write following code in your .m file.
-(IBAction)rattingsButtonTapped:(id)sender {
int currentTag = [sender tag];
for (int index = 101; index <= 110; index++) {
if ([[self.view viewWithTag:index] isKindOfClass:[UIButton class]]) {
UIButton *button = (UIButton *)[self.view viewWithTag:index];
if (button.tag <= currentTag) {
button.selected = YES;
} else {
button.selected = NO;
}
}
}
}
Step 3 - set IBAction - UITouchupInside to above methods.
you are all set, Compile and check code.

Resources