2

在我的视图控制器的初始化中,我声明了一个视图并将其设置为主视图的子视图:

self.customView = [[UIView alloc] initWithFrame:self.view.frame];
self.customView.backgroundColor = [UIColor redColor];

[self.view addSubview:self.customView];

稍后,在一种方法中,我需要替换self.customView另一种视图。(注意:更改背景颜色只是一个简化示例。视图比这更复杂)。

UIView *anotherView = [[UIView alloc] initWithFrame:self.view.frame];
anotherView.backgroundColor = [UIColor blackColor];
self.customView = anotherView;

但这没有效果。但是,如果我改为做类似的事情:

[self.view addSubview:anotherView];

它工作正常。但是,我想摆脱以前的视图,而无需显式本地化和删除视图。是不是可以在运行时替换子视图或者我错过了什么?

我与 ARC 合作。谢谢!

4

4 回答 4

4

我想对你来说最好的解决方案是为@property customView编写一个自定义设置器:

在标题中:

@property (nonatomic, strong) UIView* customView;

在实施中:

@synthesize customView = _customView;
...
-(void) setCustomView:(UIView *)customView {
    NSUInteger z = NSNotFound;
    if (_customView) {
        z = [self.view.subviews indexOfObject:_customView];
    }
    if (z == NSNotFound) {
        // old view was not in hierarchy
        // you can insert subview at any index and any view you want by default
        [self.view addSubview:customView];
    } else {
        // you can save superview
        UIVIew *superview = _customView.superview;
        [_customView removeFromSuperview];
        //also you can copy some attributes of old view:
        //customView.center = _customView.center
        [superview insertSubview:customView atIndex:z];
    }
    // and save ivar
    _customView = customView;
}

所以你不需要将你的 customView 添加为子视图。您还可以随时更换您的 customView

于 2013-08-04T17:02:29.970 回答
2

您需要删除旧视图并添加新视图。像这样的东西:

// Remove old customView
[self.customView removeFromSuperview];

// Add new customView
UIView *anotherView = [[UIView alloc] initWithFrame:self.view.frame];
anotherView.backgroundColor = [UIColor blackColor];
self.customView = anotherView;
[self.view addSubview:self.customView];

编辑:

我什至没有注意到你所做的只是改变背景颜色。在这种情况下,根本不需要替换视图。只需更新背景颜色:

self.customView.backgroundColor = [UIColor blackColor];
于 2013-08-04T16:26:35.500 回答
0

而不是删除旧的并添加新的,您可以更改旧的颜色,这将比创建/删除视图更优化。

您可以通过以下代码更改已添加的视图的颜色

self.customView.backgroundColor = [UIColor blackColor];

于 2013-08-04T16:27:33.460 回答
0

您分享的示例代码我觉得这不是正确的编码方式。按照示例代码。

初始化视图并设置隐藏属性

self.customView = [[UIView alloc] initWithFrame:self.view.frame];

self.customView.backgroundColor = [UIColor redColor];

[self.view addSubview:self.customView];

self.customView.hidden = YES;

UIView *anotherView = [[UIView alloc] initWithFrame:self.view.frame];

anotherView.backgroundColor = [UIColor blackColor];

[self.view addSubview:anotherView];

anotherView.hidden = YES;

在运行时选择您需要的视图

self.customView.hidden = NO;

anotherView.hidden = YES;

如果你需要 self.customView 来显示

anotherView.hidden = NO;

self.customView.hidden = YES;

如果您需要另一个视图来显示

于 2013-08-04T16:34:15.657 回答