UIButton修改UIImageView的图像

时间:2010-10-18 17:07:17

标签: iphone objective-c uibutton

我正在开发一款iPhone应用程序,我需要一些帮助。我创建了一个按钮,当我点击按钮时,我想要更改图像的imageView。

图像和按钮:

CGRect slot1Rect = CGRectMake(70, 90, 80, 110);
    UIImageView *slot1 = [[UIImageView alloc] initWithFrame:slot1Rect];
    [slot1 setImage:[UIImage imageNamed:@"carte_dos_rouge.png"]];
    slot1.opaque = YES; 
    [self.view addSubview:slot1];
    [slot1 release];



    UIButton *carte1J1=[UIButton buttonWithType:UIButtonTypeCustom];
    carte1J1.frame=CGRectMake(60, 240, 50, 73.0);
    [carte1J1 setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@.png",[d getlist1:0]] ] forState:UIControlStateNormal] ;
    [carte1J1 addTarget:self action:@selector (clicCarte1J1)  forControlEvents:UIControlEventTouchUpOutside];
     [self.view addSubview:carte1J1];

行动:

- (void)clicCarte1J1:(UIImageView *)slot1 {

  [slot1 setImage:[UIImage imageNamed:@"K_spades.png"]]; }

我的问题是当我点击carte1J1时没有任何反应,我应该在slot1 UIImageView上有K_spades.png图像。

2 个答案:

答案 0 :(得分:0)

    [carte1J1 addTarget:self action:@selector (clicCarte1J1)  forControlEvents:UIControlEventTouchUpOutside];

...

- (void)clicCarte1J1:(UIImageView *)slot1 {

  [slot1 setImage:[UIImage imageNamed:@"K_spades.png"]]; 
}

是什么让你认为你想要修改的UIImageView会神奇地传递给那个选择器?因为它不会。此外,您已将方法指向方法clicCarte1J1,然后实施clicCarte1j1:,这是一个完全不同的方法名称。

您需要做的是为该UIImageView创建一个@property,并在目标方法中以这种方式实现它。并在没有参数的情况下将方法名称更改为-(void)clickCarte1J1

答案 1 :(得分:0)

存在以下问题:

  • @selector与实际方法不匹配(需要冒号结尾“clickCarte1J1:”)
  • 你可能想要UIControlEventTouchUpInside而不是UIControlEventTouchUpOutside
  • click方法假设参数是UIImageView但它实际上是被点击的UIButton

要解决此问题,首先在slot1上设置tag属性,以便按钮的click方法可以在以后找到它:

CGRect slot1Rect = CGRectMake(70, 90, 80, 110);
UIImageView *slot1 = [[UIImageView alloc] initWithFrame:slot1Rect];
[slot1 setImage:[UIImage imageNamed:@"carte_dos_rouge.png"]];
slot1.opaque = YES; 
slot1.tag = 42; //use whatever number you like
[self.view addSubview:slot1];
[slot1 release];

然后将addTarget更改为:

[carte1J1 addTarget:self action:@selector (clicCarte1J1)  forControlEvents:UIControlEventTouchUpInside];

并将点击方法更改为:

- (void)clicCarte1J1 {  
    UIImageView *slot1 = (UIImageView *)[self.view viewWithTag:42];
    [slot1 setImage:[UIImage imageNamed:@"K_spades.png"]]; 
}