我的想法是将生成的整数值添加到 UIImageView 的名称中。这是一个示例:我有三个 UIImageView,分别命名为 imageView1、imageView2、imageView3。当按下按钮时,我有这个简单
self.value = value + 1;
的代码:(当然,我声明了这个“值”)现在我想添加一些代码,内容如下:
UIImage *img = [UIImage imageNamed:@"image.png"];
[imageView(value) setImage:img];
所以我希望这部分代码...[imageView(value)...
使用我上面定义的值. 我怎么能这样做?
问问题
616 次
3 回答
1
你可以tag
为你的图像视图设置一个:
// set tag
[imageView1 setTag:1];
[imageView2 setTag:2];
//...
// get the image view with the tag
[(UIImageView *)[self.view viewWithTag:value] setImage:img];
//...
于 2012-09-29T09:04:06.157 回答
1
您可以使用标签,也可以将标签UIImageViews
放入NSArray
. 然后你可以做类似的事情
[((UIImageView *)[imageViewArray objectAtIndex:self.value]) setImage:img];
于 2012-09-29T09:06:27.113 回答
1
在这里,我尝试按照您的要求进行操作。
我的 ViewController 类
- (void)viewDidLoad
{
[super viewDidLoad];
ExtendedUIImageView *eimage=[[ExtendedUIImageView alloc]initExtendedUIImageViewWithFrame:CGRectMake(0, 0, 768, 1024)];
UIImage *img1=[UIImage imageNamed:@"mac.png"];
UIImage *img2=[UIImage imageNamed:@"images.jpeg"];
UIImage *img3=[UIImage imageNamed:@"mac.png"];
[eimage addUIImage:img1 ToExtendedImageViewWithRect:CGRectMake(100, 100, 100, 100) withTag:1];
[eimage addUIImage:img2 ToExtendedImageViewWithRect:CGRectMake(210, 100, 100, 100) withTag:2];
[eimage addUIImage:img3 ToExtendedImageViewWithRect:CGRectMake(320, 100, 100, 100) withTag:3];
[self.view addSubview:eimage];
}
- (IBAction)chageImage:(UIButton *)sender {
NSLog(@"#####");
UIImage *img2=[UIImage imageNamed:@"images.jpeg"];
[eimage replaceImage:img2 forTag:3];
}
我扩展了 UIView 类并创建了新的类 ExtendedImageView 类
扩展图像视图.h
@interface ExtendedUIImageView : UIView
-(id)initExtendedUIImageViewWithFrame:(CGRect)rect;
-(void)addUIImage:(UIImage *)img ToExtendedImageViewWithRect:(CGRect)rect withTag:(int)n;
-(void)replaceImage:(UIImage *)newImg forTag:(int)n;
@end
扩展图像视图.m
@implementation ExtendedUIImageView
-(id)initExtendedUIImageViewWithFrame:(CGRect)rect{
if([super initWithFrame:rect]){
return self;
}
return nil;
}
-(void)addUIImage:(UIImage *)img ToExtendedImageViewWithRect:(CGRect)rect withTag:(int)n{
UIImageView *imgView=[[UIImageView alloc]initWithImage:img];
//[imgView setBackgroundColor:[UIColor grayColor]];
imgView.frame=rect;
[imgView setTag:n];
[self addSubview:imgView];
}
-(void)replaceImage:(UIImage *)newImg forTag:(int)n{
for(UIView * img in [self subviews]){
if([img isKindOfClass:[UIImageView class]]&&[img tag]==n){
((UIImageView *)img).image=newImg;
}
}
}
@end
于 2012-09-29T12:29:01.770 回答