【问题标题】:How to select UIImageView with name of Object如何选择具有对象名称的 UIImageView
【发布时间】:2012-03-09 23:48:48
【问题描述】:

我在 Interface Builder 中添加了 6 个 UIImageView。 那些被声明了。

@property (nonatomic, strong) IBOutlet UIImageView *Image1;

@property (nonatomic, strong) IBOutlet UIImageView *Image2;

@property (nonatomic, strong) IBOutlet UIImageView *Image3;

@property (nonatomic, strong) IBOutlet UIImageView *Image4;

@property (nonatomic, strong) IBOutlet UIImageView *Image5;

@property (nonatomic, strong) IBOutlet UIImageView *Image6;

那些 UIImageView 的名字有一个规则——“Image”+数字。

我想动态地选择那些 ImageView。 例如,

for (NSInteger i = 0; i

    if(... condition ) 
    {
       //new 
       [[NSString stringWithFormat:@"Image%d", i+1] setHidden:YES];  //--(1) 
    }
    else
    {
        [[NSString stringWithFormat:@"Image%d", i+1] setHidden:NO];  //--(2) 
    }

}

但是,这段代码不正确。 请告诉我更多的好方法。

【问题讨论】:

    标签: iphone ios uiimageview


    【解决方案1】:

    jonkroll 建议将您的图像视图放在一个数组中是一种很好的方法,而且通常性能最高。

    另一种方法是使用键值编码 (KVC) 按名称访问您的属性:

    for (int i = 0; i < 6; ++i) {
        NSString *key = [NSString stringWithFormat:@"Image%d", i + 1];
        UIImageView *imageView = (UIImageView *)[self valueForKey:key];
        imageView.hidden = condition;
    }
    

    正如 Mark 所建议的,使用 view 标签是第三种方法。他的回答有点缺乏细节,所以我会提供一些。

    您可以在笔尖中设置标签:

    因此您可以将Image1 图像视图的标签设置为1,将Image2 图像视图的标签设置为2,依此类推。

    然后你可以在顶层视图上使用viewWithTag: 方法通过标签找到一个图像视图:

    for (int i = 0; i < 6; ++i) {
        [self.view viewWithTag:i+1].hidden = condition;
    }
    

    【讨论】:

    • 非常感谢,抢!! :D
    • 我喜欢第一种方式,键值编码。好一个 Rob :)
    【解决方案2】:

    创建一个图像视图数组并使用快速枚举对其进行迭代:

    NSArray *imageViewArray = [NSArray arrayWithObjects:self.Image1,self.Image2,self.Image3,self.Image4,self.Image5,self.Image6,nil];
    
    for (UIImageView* imageView in imageViewArray) {
    
        if(... condition ) {
           [imageView setHidden:YES];  //--(1) 
        } else {
            [imageView setHidden:NO];  //--(2) 
        }
    }
    

    【讨论】:

      【解决方案3】:

      通常您可以使用 Tag 来标识您的视图,而不是使用视图的名称。

      @property(nonatomic) NSInteger 标签

      看这里:

      https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIView_Class/UIView/UIView.html

      设置标签后,您可以执行以下操作 if(uiview.tag == kSomeButtonTag)

      【讨论】:

        猜你喜欢
        • 2020-12-31
        • 2014-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-03
        • 2021-02-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多