我在数组中添加 UIViews。单击按钮后,我将它们添加到另一个 View 中。完美运行。
问题是,当我在数组中多次添加 View 时。 View 只设置一次。
这是我的代码。
-(IBAction)buttonClick:(id)sender {
UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
view1.backgroundColor = [UIColor redColor];
UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
[view2 setBackgroundColor:[UIColor orangeColor]];
UIView *view3 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
[view3 setBackgroundColor:[UIColor greenColor]];
UIView *view4 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
[view4 setBackgroundColor:[UIColor blueColor]];
NSArray *views = [NSArray arrayWithObjects:view2, view2, view1, view4, view3, nil];
[self setViews:views];
}
-(void) setViews:(NSArray*)views {
[testView1 addSubview: [views objectAtIndex:0]];
[testView2 addSubview: [views objectAtIndex:1]];
[testView3 addSubview: [views objectAtIndex:2]];
[testView4 addSubview: [views objectAtIndex:3]];
[testView5 addSubview: [views objectAtIndex:4]];
}
输出为
对于
NSArray *views = [NSArray arrayWithObjects:view1, view2, view4, view4, view3, nil];
,输出为 对于
NSArray *views = [NSArray arrayWithObjects:view1, view2, view3, view4, view4, nil];
,输出为 我说得更清楚了。对于
[NSArray arrayWithObjects:view1, view1, view1, view1, view1, nil];
, testView1,2,3,4 为空,view1
已添加到 testView5
.无论添加多少次 View ,如何才能带来完美的输出?
我想听听你的解释..!
最佳答案
来自 Apple docs
Views can have only one superview. If view already has a superview and that view is not the receiver, this method removes the previous superview before making the receiver its new superview.
这意味着,调用
addSubview
多次添加相同的 subview 只会在 super View 上添加一次(因为接收者将是相同的)。解决方案 :您将必须制作要作为 subview 重复的 View 的多个副本。
希望有帮助!
关于iphone - 数组中缺少 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19175203/