在我的 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/