ios - 在 iOS 运行时更改 subview

标签 ios objective-c uiview

在我的 View Controller 的初始化中,我声明了一个 View 并将其设置为主视图的 subview :

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

[self.view addSubview:self.customView];

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

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

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

[self.view addSubview:anotherView];

它工作正常。但是,我想在不显式本地化和删除 View 的情况下摆脱以前的 View 。是否可以在运行时替换 subview ,或者我遗漏了什么?

我在 ARC 工作。谢谢!

最佳答案

我认为对您来说最好的解决方案是为@property customView 编写自定义 setter :

在标题中:

@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;
}

因此您不需要将自定义 View 添加为 subview 。 此外,您还可以随时更换您的自定义 View

关于ios - 在 iOS 运行时更改 subview ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18045006/

相关文章:

android - Kotlin Native 编译 jar 和框架

ios - 在堆叠的 UIWindows 之间传递触摸?

ios - 当应用程序在后台运行时,我可以调用网络服务电话吗

iphone - 在iphone的webview中打开下载的文件

ios - 无法在 iOS 中的 MasterVC 和 DetailVC 之间传递数据

ios - UIView是隐藏函数, "the view' s next valid key view”是什么意思?

ios - 为什么在为 subview 添加图层蒙版时需要调用 layoutIfNeeded()?

ios - performSegueWithIdentifier 需要一分钟以上的时间来执行或崩溃

ios - 使用字典作为模型

ios - 约束更新后,UIView 的边界什么时候改变?