布局子视图时的奇怪行为

时间:2013-05-24 02:24:42

标签: objective-c uiscrollview interface-builder

我正在创建一个用户可以使用UIScrollView浏览多个视图的UI。我在代码中创建UIView对象并将它们添加到UIScrollView。我使用下面的代码创建视图。

CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;

UIView *brandView = [[UIView alloc] initWithFrame:frame];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 50.0, frame.size.width, 30)];
label.text = [brand objectForKey:@"name"];
label.textAlignment = UITextAlignmentCenter;
label.backgroundColor = [UIColor redColor];
[brandView addSubview:label];

UIImageView *logoImageView = [[UIImageView alloc] init];
logoImageView.frame = CGRectMake(20.0, 100.0, 280.0, 300.0);
[brandView addSubview:logoImageView];
logoImageView.file = [brand objectForKey:@"logo"];
[logoImageView loadInBackground];

虽然我为标签的y坐标给出50.0,但在运行应用程序时根本看不到标签。而logoImageView的顶部有100.0,但它出现在状态栏的下方,好像它的y坐标为0.0。

这种奇怪的行为是什么原因,我做错了什么?

注意:IB上禁用UIScrollView的自动布局。

1 个答案:

答案 0 :(得分:0)

以下代码适合您!

CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * 10;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;

UIView *brandView = [[UIView alloc] init]; // CHANGE THAT HAS TO BE DONE

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 50.0, self.scrollView.frame.size.width, 30)];
label.text = @"Test";
label.textAlignment = UITextAlignmentCenter; // DEPRECATED IN iOS 6.0
label.backgroundColor = [UIColor redColor];
[brandView addSubview:label];
[self.scrollView addSubview:brandView];