我正在尝试以编程方式使两个视图共享父视图的宽度。我曾尝试使用init作为子视图和initWithFrame,但在任何一种情况下,我都无法使拉伸正常工作。在下面的例子中,我希望看到一个红色窗口跨越屏幕宽度的一半,绿色窗口填充另一半。我错过了什么?
self.view = [[UIView alloc] initWithFrame:self.window.frame];
self.left = [[UIView alloc] init];
self.right = [[UIView alloc] init];
[self.left setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight)];
[self.right setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight)];
[self.view setBackgroundColor:[UIColor blueColor]];
[self.left setBackgroundColor:[UIColor redColor]];
[self.right setBackgroundColor:[UIColor greenColor]];
[self.left setContentMode:UIViewContentModeScaleToFill];
[self.right setContentMode:UIViewContentModeScaleToFill];
[self.view addSubview:self.left];
[self.view addSubview:self.right];
[self.view setAutoresizesSubviews:YES];
[self.window addSubview:self.view];
谢谢!
答案 0 :(得分:1)
您永远不会设置2个视图的初始帧。
此代码已经过测试并在UIViewController中工作
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect fullFrame = self.view.frame;
// position left view
CGRect leftFrame = fullFrame;
leftFrame.size.width = leftFrame.size.width / 2;
self.left = [[UIView alloc] initWithFrame:leftFrame];
// position right view
CGRect rightFrame = leftFrame;
rightFrame.origin.x = rightFrame.size.width;
self.right = [[UIView alloc] initWithFrame:rightFrame];
[self.left setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight)];
[self.right setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight)];
[self.view setBackgroundColor:[UIColor blueColor]];
[self.left setBackgroundColor:[UIColor redColor]];
[self.right setBackgroundColor:[UIColor greenColor]];
[self.left setContentMode:UIViewContentModeScaleToFill];
[self.right setContentMode:UIViewContentModeScaleToFill];
[self.view addSubview:self.left];
[self.view addSubview:self.right];
[self.view setAutoresizesSubviews:YES];
}
答案 1 :(得分:0)
尝试设置您添加到主视图的子视图的一些初始帧。这应该有所帮助:
self.left.frame = CGRectMake(0, 0, self.window.frame.size.width/2, self.window.frame.size.height);
self.right.frame = CGRectMake(self.window.frame.size.width/2, 0 , self.window.frame.size.width/2, self.window.frame.size.height);