我有大约10个名为pop1 to pop10的UIImageView控件。
我在UIImageView上每个都有10个按钮。这些按钮有一个从1到10的“标签”,所以我知道哪个按钮被按下了:
UIButton * aButton =(UIButton *)sender;
aButton.tag - gives me the tag
我想引用按钮下面的UIImageView,以便在按钮上方的按钮被按下时更改其图像:
UIImage *image = [UIImage imageNamed: @"NewImage.png"];
[pop1 setImage:image];
但在上面的代码中,我不想硬编码"pop1“或"pop2”等,我想使用按钮标记构建一个字符串
NSString *img = [NSString stringWithFormat:@"pop%d",aButton.tag];
给出"pop1“或"pop2”等,因为我使用的是aButton.tag。
那么,使用这些信息,我如何编写代码来引用UIImage来更改其图像呢?
在他的代码行中,"pop1“需要更改,以便使用构建的字符串- img:
[pop1 setImage:image];
我不想为每个标记键入switch语句,因为稍后我打算添加大量这样的控件,而这不是一个选项。
有没有什么方法,或者我可以使用的其他方法?
更新
我尝试了John给出的答案,代码如下
-(IBAction)pop:(id)sender{
UIButton * aButton =(UIButton *)sender;
NSLog(@"clicked button with TAG %d",aButton.tag);
if (aButton.tag > 0) {
UIImageView *img = (UIImageView *)[self.view viewWithTag:aButton.tag];
UIImage *ix = [UIImage imageNamed:@"Newimage.png"];
[img setImage:ix];
// stop any more clicks
aButton.tag = 0;
}
}
一切正常,但在运行时,我得到了一个错误,因为"img“在调试窗口中显示为"UIButton”,而不是UIImage (我认为)。
我完全对此感到困惑,因为在IB中,控件显示为Class:UIImageView,但在代码中,我将其引用为UIImage?它们可以互换吗?
如何访问"UIImageView -显示由图像数组描述的单个图像或动画(帮助)“的"tag”属性
基本上,这些按钮也有一个标签,所以如果点击按钮2,它的标签就是2。所以我想用标签=2来改变UIImageView的图像,依此类推。
我目前正在学习C/C,在大多数其他语言中,这样一个简单的任务在这方面是如此乏味。
我不知所措。请帮帮忙。
发布于 2012-10-13 11:23:32
将UIImageView
标记-1指定为-10,然后将pop
函数替换为:
-(IBAction)pop:(id)sender{
UIButton * aButton =(UIButton *)sender;
NSLog(@"clicked button with TAG %d",aButton.tag);
if (aButton.tag > 0) {
UIImageView *img = (UIImageView *)[self.view viewWithTag:(aButton.tag*-1)];
UIImage *ix = [UIImage imageNamed:@"Newimage.png"];
[img setImage:ix];
// stop any more clicks
}
}
发布于 2011-08-08 04:03:11
把标签放在相关的视图上-比如说101-110,然后取按钮标签,加100,然后用这个数字调用viewWithTag……
发布于 2011-08-08 04:24:13
我建议你用UIButton代替UIImageView。将您的图像设置为按钮图像,并为其添加标签,但是这将使您的用户单击该图像,而不是单独的按钮。
https://stackoverflow.com/questions/6977495
复制