[myScrollView addSubview:myLabel];
[myLabel release];
添加视图发生在父(容器)视图中,而不是正在添加的视图中。
此外,一旦它被添加到 superview,superview 就拥有它,您应该释放它。
编辑:OP 问道,“但是当我创建 10 个它们时会发生什么情况?”
没有。每个 UIView 子类(UIScrollView 和 UILabel 都是)都有一个 .frame 属性,其中包含一个 CGRect 结构。该字段定义对象的位置和大小。
所以:
UILabel *one = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 30)];
UILabel *two = [[UILabel alloc] initWithFrame:CGRectMake(0, 35, 200, 30)];
UILabel *three = [[UILabel alloc] initWithFrame:CGRectMake(0, 70, 200, 30)];
[myScrollView addSubview:one];
[myScrollView addSubview:two];
[myScrollView addSubview:three];
[one release];
[two release];
[three release];
这将放置三个 UILabel,每个 200px 宽 x 30px 高在滚动视图上,它们都与该视图的左侧齐平,一个在顶部右侧,一个向下 35 px,一个向下 70 px .
如果 UIScrollView 的内容大于 UIScrollView 的 .frame,则设置一个 .contentSize 属性(同样是一个 CGRect)来定义您想要滚动的内容区域。