OGeek|极客世界-中国程序员成长平台

标题: objective-c - 将 View 添加到 ScrollView [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 23:49
标题: objective-c - 将 View 添加到 ScrollView

我的 View Controller 中有一个 ScrollView 。我还创建了一个 View 并将其连接到一个 IBOutlet 变量。我需要向 Scroll View 添加许多 View 。

将 View 添加到 ScrollView 的代码:

在 .h 文件中

UIView *customView_;

@property (nonatomic, retain) IBOutlet UIView *customView;

在 .m 文件中:

@synthesize customView = customView_;

    for (int i = 0; i < 2; i++) {

        UIView *tempView = customView;
        tempView.frame = CGRectMake(i * 187, 0, 187, 133);
        [scrollView addSubview:tempView];
    }

但是使用上面的代码,我只能在位置看到一个:187,0,187,133。如果我将代码更改为 for (int i = 0; i < 3; i++) { 我只能在 374,0,187,133 中看到 View 。谁能帮我解决这个错误?



Best Answer-推荐答案


为什么会这样?

Documentation for addSubview:

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.

使用此代码

UIView *tempView = customView;
tempView.frame = CGRectMake(i * 187, 0, 187, 133);
[scrollView addSubview:tempView];

您正尝试将 相同 View 添加两次/三次。使用文档中的注释,这将删除前一个,并将其添加到新位置。 (虽然在您的情况下,superview 是接收者,但这并不意味着它会复制您的 View 并再次添加它)。

解决方案

很遗憾,UIView 不遵循 NSCopying 协议(protocol)。因此,您不能使用 copy 创建它的直接副本。您需要创建一个工厂方法来为您创建 View ,如下所示:

-(UIView)createCustomView {
    ...
}

然后在你的 for 循环中调用它:

UIView *tempView = [self createCustomView];
tempView.frame = CGRectMake(i * 187, 0, 187, 133);
[scrollView addSubview:tempView];

这可能超出 .xib 文件的范围。引用 this answer关于如何让它与 Interface Builder 配合得很好。

关于objective-c - 将 View 添加到 ScrollView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13471510/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4