在iOS中运行时更改子视图

时间:2013-08-04 16:23:38

标签: ios objective-c uiview

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

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 个答案:

答案 0 :(得分:4)

我认为最适合您的解决方案是将自定义setter写入@property customView:

标题中的

@property (nonatomic, strong) UIView* customView;

in impelementation:

@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

答案 1 :(得分: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];

答案 2 :(得分:0)

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

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

  

self.customView.backgroundColor = [UIColor blackColor];

答案 3 :(得分: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;

如果您需要另一个View来显示

相关问题