I am using this code for displaying Images in scroll view... In this buttons are created with the help of for loop... and then set image for every buttons... Now i want to select multiple images... I want when i click on particular button, its image replace with "tick image" and when i again pressed on it, replace with original image means show unchecked..
for(int i=0; i<[imageArray count]; i++)
{
if((i%4) == 0 && i!=0)
{
horizontal = 8.0;
vertical = vertical + 70.0 + 8.0;
}
buttonImage = [UIButton buttonWithType:UIButtonTypeCustom];
[buttonImage setFrame:CGRectMake(horizontal, vertical, 70.0, 70.0)];
[buttonImage setTag:i];
[buttonImage setImage:[arrayOfImages objectAtIndex:i] forState:UIControlStateNormal];
[buttonImage addTarget:self action:#selector(buttonImagePressed:) forControlEvents:UIControlEventTouchUpInside];
[myScrollView addSubview:buttonImage];
horizontal = horizontal + 70.0 + 8.0;
}
I tried this code for image changed on state change in (buttonImagePressed) method...
[buttonImage setImage:[UIImage imageNamed:#"Checkmark.png"] forState:UIControlStateSelected];
but it doesn't work... and it change only image of last button every time instead of particular clicked button.... I also tried to hide the button but it again hide only last button. where i m doing wrong???
there is any another way to change it??? please help me
Instead of UIControlStateSelected you should use UIControlStateNormal and keep some bool value which shows whether that button is previously selected or not or you can set selected property of button to true or false based on selection say:
-(void) buttonImagePressed:(UIButton*)sender
{
UIButton *button = sender;
if(button.selected) //already selected so now it should be deselected
{
[button setImage:[UIImage imageNamed:#"UnCheckmark.png"] forState:UIControlStateNormal];
button.selected = false;
}
else
{
[button setImage:[UIImage imageNamed:#"Checkmark.png"] forState:UIControlStateNormal];
button.selected = true;
}
}
For this, Take a global flag variable as BOOL Flag = NO;
Set tag for each button also.
In the method
-(IBAction)buttonImagePressed:(UIButton *)sender{
if(flag==NO){
flag=YES;
[sender setImage:[UIImage imageNamed:#"Checkmark.png"] forState:UIControlStateNormal];
}
else{
flag=NO;
[sender setImage:[arrayOfImages objectAtIndex:sender.tag] forState:UIControlStateNormal];
}
}
Related
I am new to i phone programming.I have create custom button inside that i am attaching images for each and every custom button.Now that custom button images is displaying in thumbnail.Now what i want if i select any thumbnail image or custom button.Here i want to select and deselect that thumbnail images and I want to store that selected images tag value in array.How to do this Below one my code.Using below code i am creating custom button and attaching image to custom button.
blaukypath =[[NSMutableArray alloc]init];
for (NSString* path in array)
{
[blaukypath addObject:[UIImage imageWithContentsOfFile:path]];
NSLog(#"%#",path);
}
myScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0.0, 0.0, 320.0, 840.0)];
myScrollView.delegate = self;
myScrollView.contentSize = CGSizeMake(320.0, 840.0);
myScrollView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:myScrollView];
float horizontal = 8.0;
float vertical = 8.0;
for(int i=0; i<[blaukypath count]; i++)
{
if((i%4) == 0 && i!=0)
{
horizontal = 8.0;
vertical = vertical + 70.0 + 8.0;
}
buttonImage = [UIButton buttonWithType:UIButtonTypeCustom];
[buttonImage setFrame:CGRectMake(horizontal, vertical, 70.0, 70.0)];
[buttonImage setTag:i];
[buttonImage setImage:[blaukypath objectAtIndex:i] forState:UIControlStateNormal];
[buttonImage addTarget:self action:#selector(buttonImagePressed:) forControlEvents:UIControlEventTouchUpInside];
[myScrollView addSubview:buttonImage];
horizontal = horizontal + 70.0 + 8.0;
}
[myScrollView setContentSize:CGSizeMake(320.0, vertical + 78.0)];
[self.myScrollView addSubview:buttonImage];
Now if select any thumbnail image i want to select and deselect the thumbnail images and selected thumbnail images i want to store in array.
-(void)buttonImagePressed:(id)sender
{
UIButton *btn = (UIButton*)sender;
if (btn.tag==0)
{
[btn setImage:[UIImage imageNamed:#"Default.png"] forState:UIControlStateNormal];
btn.tag=1;
}
else{
[btn setImage:nil forState:UIControlStateNormal];
btn.tag=0;
}
some body told that by using above code i will work for but i not working Exactly what i want.i want to select and deselect and also selected images i want to store in array.
Thanks
Aslam
Set the images for button asper the UIControlState
#property(nonatomic,retain)NSMutableArray *tapCollection;
[btn setImage:[UIImage imageNamed:#"buttonBackGround.png"] forState:UIControlStateNormal];
[btn setImage:[UIImage imageNamed:#"Button_Selected.jpg"] forState:UIControlStateSelected];
-(void)viewDidLoad{
self.tapCollection = [[NSMutableArray alloc] init];
}
-(void)buttonImagePressed:(id)sender
{
UIButton *selectedButton = (UIButton *)sender;
//If checked, uncheck and visa versa
[selectedButton setSelected:![selectedButton isSelected]];
if([selectedButton isSelected])
{
[self.tapCollection addObject:[NSNumber numberWithInt:btn.tag]];
}
else
{
//remove btn.tag from self.tapCollection
}
}
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;
}
I have created scroll view and sets the buttons are in the scroll view. The Buttons are scrolling horizontally and it works fine. If i clicked the button, i set background image as "Selected State" in button. My problem is how can i changed the selected state in different button, when clicking it and how can i deselected the "selected state" button when clicking the another button.
I have three buttons in the scroll view,
-(IBAction) Button1 : (id) sender
{
// btn1.selected = YES;
[btn1 setImage:[UIImage imageNamed:#"first.png"] forState:UIControlStateSelected];
}
-(IBAction) Button2 : (id) sender
{
// btn2.selected = YES;
[btn2 setImage:[UIImage imageNamed:#"second.png"] forState:UIControlStateSelected];
}
-(IBAction) Button3 : (id) sender
{
// btn3.selected = YES;
[btn3 setImage:[UIImage imageNamed:#"three.png"] forState:UIControlStateSelected];
}
see the below image,(Health, Entertainment and Money Watch are the three buttons)
Image http://www.freeimagehosting.net/uploads/6b3daab12f.png
and
Img http://www.freeimagehosting.net/uploads/b6e0f234dc.png
Note:(Like, Tabbar and Segmented control)
On clicking first button and sets background image in selected state and clicking the second button, then first buttons are to be deselected. So how can i maintain the selected state, till another button is clicked.
Thanks in Advance.
I solved this task in the following way:
init method:
Create number of buttons with defined images for normal and selected state.
Assign tag for each button (for example, for i'th button tag is 1000+i).
Assign IBAction for each button.
action method:
Remove selection from previously selected button (search it by it's tag with [view viewWithTag:] method)
Select sender.
Save sender's tag.
Here's the code:
- (void)init {
....INITIALIZE SCROLLVIEW HERE.....
for ( int i = 0; i < 10; i++ ) {
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:.....];
[btn setImage:_IMAGE_ forState:UIControlStateNormal];
[btn setImage:_IMAGE2_ forState:UIControlStateSelected];
[btn setTag:i + 1000];
[btn addTarget:self action:#selector(setSelectedButton:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:btn];
}
}
- (IBAction)setSelectedButton:(id)sender {
[self setSelectedButtonByIndex:((UIButton *)sender).tag - 1000];
}
- (void)setSelectedButtonByIndex:(NSInteger)index {
if ( selectedElemId >= 0 ) {
UIButton *btn = (UIButton *)[self viewWithTag:selectedElemId + 1000];
[btn setSelected:NO];
}
UIButton *btn = (UIButton *)[self viewWithTag:index + 1000];
[btn setSelected:YES];
selectedElemId = btn.tag - 1000;
}
I want to programmatically add multiple UIButtons to a view - the number of buttons is unknown at compile time.
I can make one or more UIButton's like so (in a loop, but shorted for simplicity):
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchDown];
[button setTitle:#"Button x" forState:UIControlStateNormal];
button.frame = CGRectMake(100.0, 100.0, 120.0, 50.0);
[view addSubview:button];
Copied/Edited from this link:
How do I create a basic UIButton programmatically?
But how do I determine in buttonClicked: which button was clicked? I'd like to pass tag data if possible to identify the button.
You could either keep a reference to the actual button object somewhere that mattered (like an array) or set the button's tag to something useful (like an offset in some other data array). For example (using the tag, since this is generally must useful):
for( int i = 0; i < 5; i++ ) {
UIButton* aButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[aButton setTag:i];
[aButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[aView addSubview:aButton];
}
// then ...
- (void)buttonClicked:(UIButton*)button
{
NSLog(#"Button %ld clicked.", (long int)[button tag]);
}
You can assign a tag to the button.
button.tag = i;
Then in -buttonClicked:, check the tag of the sender:
-(void)buttonClicked:(UIButton*)sender {
int tag = sender.tag;
...
}
I think this would be the best answer:-
http://conecode.com/news/2012/05/ios-how-to-create-a-grid-of-uibuttons/
For that give different tag to each button & use code like this:
[btn1 addTarget:self action:#selector(pressbtn:) forControlEvents:UIControlEventTouchUpInside];
[btn2 addTarget:self action:#selector(pressbtn:) forControlEvents:UIControlEventTouchUpInside];
& in method
-(void)pressbtn:(id)sender {
UIButton *button=sender;
if (button.tag==1)
{
NSLog(#"Press button 1");
}
if (button.tag==2)
{
NSLog(#"Press button 2");
}
and so on to check which button is called
If you want to add buttons at run time then there will be 10 20 50 or more than that. Then you should to use ui scroll view in this condition.
When the buttons will be generate then your scroll view size should be increased accordingly.
And you can write the code like this
scrollview = [[UIScrollView alloc] init];
scrollview.contentSize = CGSizeMake(INVOICE_ADDITEM_SCROLLVIEW_CONTENT_WIDTH, INVOICE_ADDITEM_SCROLLVIEW_CONTENT_HEIGHT);
scrollview.frame = CGRectMake(0,50, SCROLLVIEW_WIDTH, SCROLLVIEW_HEIGHT);
// scrollview.backgroundColor = [UIColor whiteColor];
scrollview.scrollsToTop = NO;
scrollview.delegate = self;
[self.view addSubview:scrollview];
for (int pos = 0; pos < 2; pos++) {
UIButton *but = [UIButton buttonWithType:UIButtonTypeCustom];
[but setImage:[UIImage imageNamed:#"checkbox.png"] forState:UIControlStateNormal];
[but setImage:[UIImage imageNamed:#"checkbox_active.png"] forState:UIControlStateSelected];
[but setFrame:CGRectMake(TXT_FLD_X_CORD+90, 295, 20, 20)];
// [but setCenter:CGPointMake( 50, i*40+20 )];
but.tag = pos;
/*if(pos==0)
{
[but setImage:[UIImage imageNamed:#"checkbox_active.png"] forState:UIControlStateNormal];
// [but setImage:[UIImage imageNamed:#"checkbox_active.png"] forState:UIControlStateSelected];
}*/
[but setCenter:CGPointMake(pos*90+125 ,310)];
[but addTarget:self action:#selector(checkboxButton:) forControlEvents:UIControlEventTouchUpInside];
[scrollview addSubview:but];
}
UIButton has a tag property. Use that and in your buttonClicked method, you can check the button that was clicked based on it's tag. Might want to keep constants around for what button is what.
For each of your buttons set an appropriate tag, and then refer to the tag in your action. i.e.
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
...
button.tag = 1
[view addSubview:button];
You can easily set the tag based on the index of your iteration, if you're creating buttons in a loop. And then in your action:
- (void)aButtonWasTapped:(UIButton *)source {
if( source.tag == 1 ) {
// etc
}
}
Somebody might have this problem:
Jason Coco's answer worked fine for me, until I wanted to use the tag to access properties from an NSArray that was defined as a property.
Turns out the property had to be defined as "retain" instead of "weak".
The Swift version (with Labels):
for index in 1...5 {
var label = UILabel()
label.tag = index
labelsDictionary["Label\(index)"] = label
self.addSubview(label)
}
Call using using self.viewWithTag(i) as UILabel:
(cell.viewWithTag(5) as UILabel).text
I am trying to make a standard check box for my iPhone app from a UIButton with a title and image. The button image changes between an "unchecked" image and a "checked" image.
At first I tried subclassing UIButton but UIButton has no -init*** method to use in my -init method.
What is the best way to do this?
Thanks in advance.
You shouldn't need to subclass the UIButton class. By design, Objective-C favors composition over inheritance.
UIButton is a subclass of UIControl, which has a selected property. You can use this property to toggle the on/off behaviour of a checkbox, just the same way a UISwitch does.
You can attach an action to the button's touched up inside event, and perform the toggling in there, something like this:
// when you setup your button, set an image for the selected and normal states
[myCheckBoxButton setImage:checkedImage forState:UIControlStateSelected];
[myCheckBoxButton setImage:nonCheckedImage forState:UIControlStateNormal];
- (void)myCheckboxToggle:(id)sender
{
myCheckboxButton.selected = !myCheckboxButton.selected; // toggle the selected property, just a simple BOOL
}
Set the images in the button:
[button setImage:uncheckedImage forState:UIControlStateNormal]
[button setImage:checkedImage forState:UIControlStateSelected]
Now all you need to do is:
button.selected = state
and the correct images will display.
All you need to do is set 2 different images for the states UIControlStateNormal and UIControlStateSelected, then in your selector, changed the selected property of the button.
Here is a working example (replace image names with your own):
- (void)loadView {
// ...
UIButton *chkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[chkBtn setFrame:CGRectMake(0, 0, 300, 25)];
[chkBtn setImage:[UIImage imageNamed:#"UNCHECKED.png"]
forState:UIControlStateNormal];
[chkBtn setImage:[UIImage imageNamed:#"CHECKED.png"]
forState:UIControlStateSelected];
[chkBtn addTarget:self
action:#selector(chkBtnHandler:)
forControlEvents:UIControlEventTouchUpInside];
// Optional title change for checked/unchecked
[chkBtn setTitle:#"I am NOT checked!"
forState:UIControlStateNormal];
[chkBtn setTitle:#"I am checked!"
forState:UIControlStateSelected];
[self.view addSubview:chkBtn];
[chkBtn release], chkBtn = nil;
// ...
}
- (void)chkBtnHandler:(UIButton *)sender {
// If checked, uncheck and visa versa
[sender setSelected:!sender isSelected];
}
For anyone interested in the future - instead of doing it yourself just download the link below from GitHub and it has it subclassed from UIControl already and functions perfectly as a checkbox. Also includes a sample project on how easy it is to use:
https://github.com/Brayden/UICheckbox
I have used M13Checkbox in one of my projects. Works ok.
https://github.com/Marxon13/M13Checkbox
Did you try overriding the initWithCoder method, just in case it is loaded from a nib somehow?
UIImage* nonCheckedImage=[UIImage imageNamed:#"ic_check_box_outline_blank_grey600_48dp.png"];//[UIImage init
UIImage* CheckedImage=[UIImage imageNamed:#"ic_check_box_black_48dp.png"];//[UIImage init
//ic_check_box_black_48dp.png
[_checkBox setImage:CheckedImage forState:UIControlStateSelected];
[_checkBox setImage:nonCheckedImage forState:UIControlStateNormal];
}
- (IBAction)checkBoxToggle:(id)sender {
_checkBox.selected = !_checkBox.selected; // toggle the selected property, just a simple BOOL
}
the image you can use google icon
Try this:-
-(IBAction)clickCheckButton:(UIButton *)sender {
if (sender.tag==0) {
sender.tag = 1;
[sender setImage:[UIImage imageNamed:#"check.png"] forState:UIControlStateNormal];
}else
{
sender.tag = 0;
[sender setImage:[UIImage imageNamed:#"uncheck.png"] forState:UIControlStateNormal]; } } sender.tag = 0;
[sender setImage:[UIImage imageNamed:#"uncheck.png"] forState:UIControlStateNormal];
}
}
Why not use a switch - UISwitch? This is used to display an element showing the boolean state of a value.