I have taken all the images from photo gallery in an array and then shown all these images on UIButtons and putt them in scroll View to show a grid view.Now when user click the button it should look like as he selected that image, for that I have taken a tick mark image and added it in a UIImageView and added that image view on the button on its click. But now when user again click the same button then how to remove that UIImageview from button when user has already selected multiple images.
Here is my code
-(void)loadImagesOnScrollView
{
scrollView.contentSize=CGSizeMake(0, 55*[assets count]);
int x=0,y=0;
for (int i=0; i<[assets count]; i++) {
ALAsset *asset = [assets objectAtIndex:i];
UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
btn.frame=CGRectMake(x, y, 100, 100);
btn.tag=i;
[btn setImage:[UIImage imageWithCGImage:[asset thumbnail]] forState:UIControlStateNormal];
[btn addTarget:self action:#selector(btnClkd:) forControlEvents:UIControlEventTouchUpInside];
if(i==0)
{
}
else if(i%2 ==0)
{
x=0;
y=y+110;
}
else
{
x=x+110;
}
[scrollView addSubview:btn];
}
}
-(void)btnClkd:(UIButton*)sender
{
if (sender.selected) {
sender.selected=FALSE;
}
else
{
sender.selected=TRUE;
}
if(sender.selected)
{
[sender addSubview:imgView];
}
else
{
}
}
Along this I have one more question, how to set the content size of scroll view so as it can be adjusted with any number of images.
when you add an image on a button on selection, set its tag = constant (say 9999) + sender.tag.
Now again on click of button check if subview with tag 9999+sender.tag exists. If yes, remove that subview from superview
Create a BOOL variable in your .h file eg:
BOOL isButtonClicked; // in .h file
then in your .m file
-(IBAction)onButtonClick:(UIButton *)checkBoxButton
{
if (!isButtonClicked) {
[checkBoxButton setImage:[UIImage imageNamed:#"tickMark.png"] forState:UIControlStateNormal];
isButtonClicked=YES;
}
else
{
[checkBoxButton setImage:[UIImage imageNamed:#"NormalImage.png"] forState:UIControlStateNormal];
isButtonClicked=NO;
}
}
To check if UIImageView is added to an UIButton use the following..
for check if the button has any UIImage
if ( [button.currentImage isEqual:[NSNull null]]) {
NSLog(#"image exist");
}
or
for check if the button has any background Image
if ( [button.currentBackgroundImage isEqual:[NSNull null]]) {
NSLog(#"background image exist");
}
Related
I have two segment buttons (1 and 2) I want to add a background image one for selected segment and another image for unselected segment.How can I do that?
Here is what I have so far,should I set the background image here?:
- (void)selectWithSegment:(UIButton *)sender
{
for (UIButton *button in self.segments) {
if (button == sender) {
if (self.staySelected) {
button.backgroundColor = [UIColor colorWithRed:17.0/255.0 green:17.0/255.0 blue:17.0/255.0 alpha:1.0];
[button setBackgroundImage:nil forState:UIControlStateNormal];
}
if ([self.delegate respondsToSelector:#selector(segmentControl:didSelectSegment:)]) {
[self.delegate segmentControl:self didSelectSegment:sender];
}
} else {
[self decorateButton:button];
}
}
}
how can I set image1.png and image2.png for for selected and unselected segments?Can someone help me with the implementation?
I don't know any other way to handle this situation, but i think this can help you:
After making IBOutlet of UISegmentControl set IBAction to valueChange event with below action:
-(IBAction)selectedSegment:(id)sender{
int totalNumberOfSegment = 5;
UISegmentedControl *tmpSig = (UISegmentedControl *)sender;
NSLog(#"Inside sender method");
for (int i = 0; i < totalNumberOfSegment; i++) {
[tmpSig setImage:[UIImage imageNamed:#"unselect.png"] forSegmentAtIndex:i];
}
[tmpSig setImage:[UIImage imageNamed:#"select.png"] forSegmentAtIndex:tmpSig.selectedSegmentIndex];
}
Here my code to show the 4 button titles which one image view, I want to show the clicked alert if clicked button title is equal to the UIImageview image. Here is my code,
imageary=[[NSMutableArray alloc]initWithObjects:#"dear.jpg",#"donkey.jpg",#"elephant.jpg",#"fox.jpg",#"giraffe.jpg",#"goat.jpg",#"buffallo.jpg",#"bull.jpg",#"cow.jpg",#"crocodile.jpg", nil]; // declare array of names not images
- (NSString *) convertToDisplayName:(NSString *)actual
{
return [actual stringByDeletingPathExtension]; //return image name without extension
}
Button method
-(IBAction)methodset:(id)sender
{
int i=0;
for(UIView *view in self.view.subviews)
{
if([view isKindOfClass:[UIButton class]])
{
mybutton = (UIButton *)view;
if(mybutton.tag == 1||mybutton.tag == 2||mybutton.tag == 3||mybutton.tag == 4)
{
i = rand() % [imageary count]; // set random image
animage.image=[UIImage imageNamed:[imageary objectAtIndex:i]];
name=[self convertToDisplayName:[imageary objectAtIndex:i]];
[mybutton setTitle:name forState:UIControlStateNormal];
NSLog(#"current image name :%#",name);
i++;
}
}
}
}
Now im facing problem with
rand(), while shuffling the some values in the button are
repeating. How can i shuflle the values without repeating and show in
UIButton.
Where should I compare for the image name and clicked button title
is equal or not. Please help me to resolve this issue. Please do the
needful.
Use a while loop for the rand bit
while (i != mybutton.tag){
i = rand() % [imageary count];
}
Just compare the imagery names and uibutton title after the if(mybutton.tag ...etc etc because you want it in the for loop right? also indent your code :P. makes it easier to read.
if ([btn.titleLabel.text isEqualToString:#"imageName"])
according to your code
if ([btn.titleLabel.text isEqualToString: name])
You can simply do it by changing the function like:
-(IBAction)methodset:(id)sender
{
UIButton *mybutton = (UIButton *)sender;
if(mybutton.tag == 1||mybutton.tag == 2||mybutton.tag == 3||mybutton.tag == 4)
{
for(int loop = 0; loop<4;loop++)
{
animage.image=[UIImage imageNamed:[imageary objectAtIndex:i]];
name=[self convertToDisplayName:[imageary objectAtIndex:i]];
[mybutton setTitle:name forState:UIControlStateNormal];
NSLog(#"current image name :%#",name);
if ([mybutton.titleLabel.text isEqualToString:[imageary objectAtIndex:i]])
{
//titles equal
}
UIView *newView = [self.view viewWithTag:i];
if([newView isKindOfClass:[UIButton class]])
{
UIButton *newButton = (UIButton *)newView;
[newbutton setTitle:name forState:UIControlStateNormal];
}
}
}
}
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{
}
My application consist of several buttons , when user touch one of them a shadow appears below them, and the rest of buttons should not have any background image , I need something like Instagram application effects , here is my code but my problem is when I touched other button the shadow does not appears .
#define BGB [btn setBackgroundImage:[UIImage imageNamed:#"shadow.png"] forState:UIControlStateNormal]
#define _BGB [btn setBackgroundImage:nil forState:UIControlStateNormal]
- (IBAction)effectsPerform:(id)sender {
UIButton *btn = (UIButton *)sender;
if (btn == EB0) { BGB; } else { _BGB; }
if (btn == EB1) { BGB; } else { _BGB; }
if (btn == EB2) { BGB; } else { _BGB; }
//and other buttons ...
}
Try this way:
-(void)changeButton:(UIButton *)button background:(UIImage *)image
{
[button setBackgroundImage:image forState:UIControlStateNormal];
}
- (IBAction)effectsPerform:(UIButton *)sender
{
[self changeButton:sender background:(sender == EB0 || sender == EB1 || sender == EB2) ? [UIImage imageNamed:#"shadow.png"] : nil];
}
UPDATE:
You do it with another approach, in your viewDidLoad: method, for every button you can set:
[button setBackgroundImage:nil forState:UIControlStateNormal];
[button setBackgroundImage:[UIImage imageNamed:#"shadow.png"] forState:UIControlStateSelected];
And then in your -(IBAction)effectsPerform:
- (IBAction)effectsPerform:(UIButton *)sender
{
button1.isSelected = (sender == button1);
button2.isSelected = (sender == button2);
....
}
...this way you guarantee you will have only one selected button. What can you do to optimize your code is you can subclass UIButton and in the init method you call the background setter methods, and then all buttons can be of this type (you can mark them in the interface builder by setting their class) - this way you won't need to set the background images for every state for every button.
I have a problem with adding a set of UIButtons to a UIScrollView. With the buttons added it seems that the scroll command is not being passed to the scroll view as the buttons cover the whole surface. I've read various posts on this but still can't figure it out. I'm pretty new to iPhone programming so there's probably something obvious I've missed. I've tried things like canCancelContentTouches and delaysContentTouches to TRUE and FALSE.
Here is the code I use to add the buttons to the UIScrollView. The UIScrollView was created in IB and is passed in to the function:
-(void)drawCharacters:(NSMutableArray *)chars:(UIScrollView *)target_view {
//NSLog(#"CLEARING PREVIOUS BUTTONS");
//clear previous buttons for parts/kanji
if(target_view == viewParts){
for (UIButton *btn in parts_buttons) {
[btn removeFromSuperview];
}
[parts_buttons removeAllObjects];
} else if(target_view == viewKanji){
for (UIButton *btn in kanji_buttons) {
[btn removeFromSuperview];
}
[kanji_buttons removeAllObjects];
}
//display options
int chars_per_line = 9; //change this to change the number of chars displayed on each line
if(target_view == viewKanji){
chars_per_line = 8;
}
int char_gap = 0; //change this to change the margin between chars
int char_dimensions = (320/chars_per_line)-(char_gap*2);
//set starting x, y coords
int x = 0, y = 0;
//increment y coord
y += char_gap;
//NSLog(#"ABOUT TO DRAW FIRST BUTTON");
for(NSMutableArray *char_arr in chars){
//increment x coord
x += char_gap;
//draw at x and y
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
myButton.frame = CGRectMake(x, y, char_dimensions, char_dimensions); // position in the parent view and set the size of the button
[myButton setTitle:[char_arr objectAtIndex:0] forState:UIControlStateNormal];
[myButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
[myButton setTitleColor:[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1.0] forState:UIControlStateDisabled];
myButton.titleLabel.font = [UIFont boldSystemFontOfSize:22];
if(target_view == viewKanji){
myButton.titleLabel.font = [UIFont boldSystemFontOfSize:30];
}
// add targets and actions
if(target_view == viewParts){
[myButton addTarget:self action:#selector(partSelected:) forControlEvents:UIControlEventTouchUpInside];
} else if(target_view == viewKanji){
[myButton addTarget:self action:#selector(kanjiSelected:) forControlEvents:UIControlEventTouchUpInside];
[myButton setTag:(int)[char_arr objectAtIndex:1]];
}
//if the part isnt in the current list of kanji, disable and dim it
if(target_view == viewParts){
if([kanji count] > 0){
[myButton setEnabled:NO];
}
bool do_break = NO;
for(NSMutableArray *arr in kanji){
//NSLog([NSString stringWithFormat:#"CHECKING PARTS AGAINST %d KANJI", [kanji count]]);
for(NSString *str in [[arr objectAtIndex:2] componentsSeparatedByString:#" "]){
if(([myButton.titleLabel.text isEqualToString:str])){
//NSLog(#"--------------MATCH!!!-----------------");
[myButton setEnabled:YES];
for(NSString *str1 in parts_selected){
if(([myButton.titleLabel.text isEqualToString:str1])){
[myButton setEnabled:NO];
break;
}
}
do_break = YES;
break;
}
if(do_break) break;
}
if(do_break) break;
}
}
// add to a view
[target_view addSubview:myButton];
//update coords of next button
x += char_dimensions+ char_gap;
if (x > (320-char_dimensions)) {
x = 0;
y += char_dimensions + (char_gap*2);
}
//add button to global array to be removed from view next update
if(target_view == viewParts){
[parts_buttons addObject:myButton];
} else if(target_view == viewKanji){
[kanji_buttons addObject:myButton];
}
}
//NSLog(#"FINISHED DRAWING ALL BUTTONS");
}
Any help on this would be greatly appreciated. I just need to fix this to finish my app.
You cannot expect the scrollview to receive events if the buttons cover the whole surface.(They are going to be first in the responder chain). The quick fix would be to make the buttons slightly smaller than the scrollview.
On first read of this problem I was thinking that you wanted to add buttons to the scrollview's superview -- but then I realized you actually want the buttons in the scrollview.