如何检查单击的按钮标题等于uiimageview中的图像名称

时间:2012-11-08 07:27:01

标签: iphone ios uiimageview uibutton

这里我的代码显示4个按钮标题哪一个图像视图,我想显示点击的警告,如果点击按钮标题等于UIImageview图像。这是我的代码,

 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
 }

按钮方法

-(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++;

   }
  }
 }
}

现在我正面临着

的问题
  1. rand(),同时拖拽按钮中的一些值 重复。如何在不重复和显示的情况下避免使用这些值 的UIButton。
  2. 我应该在哪里比较图像名称和点击的按钮标题 是否平等。请帮我解决这个问题。请做 要紧的。

3 个答案:

答案 0 :(得分:0)

对rand位使用while循环

while (i != mybutton.tag){
   i = rand() % [imageary count];
}

只需比较if之后的图像名称和uibutton标题(mybutton.tag等等,因为你想要它在for循环中吗?还要缩进你的代码:P。使它更容易阅读。

答案 1 :(得分:0)

if ([btn.titleLabel.text isEqualToString:@"imageName"])  

根据您的代码

if ([btn.titleLabel.text isEqualToString: name])  

答案 2 :(得分:0)

您只需更改以下功能即可:

-(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];
        }
     }
  }
}