How to check the clicked button title is equal to

2019-08-20 05:11发布

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

  1. rand(), while shuffling the some values in the button are repeating. How can i shuflle the values without repeating and show in UIButton.
  2. 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.

3条回答
劳资没心,怎么记你
2楼-- · 2019-08-20 05:42

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];
        }
     }
  }
}
查看更多
虎瘦雄心在
3楼-- · 2019-08-20 05:44

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.

查看更多
▲ chillily
4楼-- · 2019-08-20 05:46
if ([btn.titleLabel.text isEqualToString:@"imageName"])  

according to your code

if ([btn.titleLabel.text isEqualToString: name])  
查看更多
登录 后发表回答