iphone - 数组中缺少 UIView

标签 iphone ios objective-c arrays uiview

我在数组中添加 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]];
}

输出为 enter image description here

对于 NSArray *views = [NSArray arrayWithObjects:view1, view2, view4, view4, view3, nil]; ,输出为 enter image description here

对于 NSArray *views = [NSArray arrayWithObjects:view1, view2, view3, view4, view4, nil]; ,输出为 enter image description here

我说得更清楚了。对于 [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/

相关文章:

iPhone:创建类似 Facebook 的 UI、皮肤应用程序,不遵循 AHIG

ios - AVAudioSession模式切换音量差异

ios - 通过 MagicalRecords 在不同的线程中使用 NSManagedObject

objective-c - 如何更改水平 UITableView 的反弹区域的颜色/背景

iphone - 当用户在 DatePicker 控件中使用 objective-c 选择特定日期和时间时,我想在标签中显示日期和时间

ios - 获取 NSMutableArray 中最后一个重复字符串的索引

javascript - iPhone 网络中的 .focus() 问题

iPhone:如何与外部设备通信?

ios - 如何浏览文本字段(下一步/完成按钮)

javascript - HTML Canvas 线条透明度不适用于移动 Safari