对象名称 (xcode) 内的整数值



我的想法是将生成的整数值添加到UIImageView的名称中。下面是一个示例:我有三个 UIImageViews,分别名为 imageView1、imageView2、imageView3。当按下按钮时,我有这个简单的代码: self.value = value + 1;(当然我声明了这个"价值")现在我想添加一些代码,内容如下: UIImage *img = [UIImage imageNamed:@"image.png"]; [imageView(value) setImage:img];因此,我希望这部分代码...[imageView(value)...使用我上面定义的值。我该怎么做?

您可以

为图像视图设置tag

// set tag
[imageView1 setTag:1];
[imageView2 setTag:2];
//...
// get the image view with the tag
[(UIImageView *)[self.view viewWithTag:value] setImage:img];
//...

您可以使用标签,也可以将UIImageViews放入NSArray中。然后你可以做一些类似的事情

[((UIImageView *)[imageViewArray objectAtIndex:self.value]) setImage:img];

在这里,我尝试根据您的要求进行操作。

我的视图控制器类

- (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 类

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

ExtendedImageView.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

相关内容

  • 没有找到相关文章

最新更新