为什么我不能使用 StoryBoard 从 viewWithTag 方法访问嵌套的 UIView?

Why can't I access to nested UIView from viewWithTag method using StoryBoard?

我在 Storyboard 的嵌套 UIView 中创建了一些 UIImageView,并为每个 UIImageView 创建了不同的 TAG。根据故事板,ViewController 的树是这样的:

我必须以编程方式更改这些 ImageView,因此,为了获取图像,我使用方法 viewWithTag 但它不起作用,因为它 returns NIL。 即使我将 class 添加到 ViewNested IBOutlet 并使用以下代码获取视图,也会发生这种情况:

// View is the top View with Tag:40            
UIView * view = [self.view viewWithTag:40]; //This works
// The nestedView with Tag:44          
UIView * viewNested = [view viewWithTag:44]; //DOESN'T work it returns NIL even if the TAG is exact

然后,如果我尝试使用相同的方法访问 imageView,当然会 returns NIL。不知道为什么,我也试过用这段代码查看所有的递归嵌套视图,但似乎它们不存在,即使它们存在于故事板中。

- (void)showAllSubView:(UIView *)view
{   int i = 0;
    for (UIView * subView in [view subviews]) {
        NSLog(@"%@, tag:%ld", subView, (long)subView.tag) ;
        [self showAllSubView:subView] ;
        i++;
    }
    NSLog(@"Numb of Views %d", i) ;

}

根视图的标签为 40,嵌套视图的标签为 44,图像的标签为 1,2,3,4。所以TAGS都不一样。

任何帮助将不胜感激:)。提前致谢

UIImageView *imageView=(UIImageView *)[self.view viewWithTag:yourTag];
[imageView setImage:[UIImage imageNamed:@"yourImageName"]];

将 yourTag 替换为 UIImageView 标签; 用一些图像名称替换 yourImageName

如果您只想更改 ImageView 的图像 - 您不需要

UIView * view = [self.view viewWithTag:40]; //This works
// The nestedView with Tag:44          
UIView * viewNested = [view viewWithTag:44];

您还可以更改所有图片:

for (int i=0; i<18; i++)
    {
            UIImageView *imageView=(UIImageView *)[self.view viewWithTag:i];
NSString *imageName = [NSString stringWithFormat:@"imageName_%d", i];
    [imageView setImage:[UIImage imageNamed:imageName]];
    }