0

我正在尝试以编程方式使两个视图共享父视图的宽度。我尝试过为子视图和 initWithFrame 使用 init,但无论哪种情况,我都无法让拉伸正常工作。在下面的示例中,我希望看到一个跨越屏幕一半宽度的红色窗口和一个填充另一半的绿色窗口。我错过了什么?

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];

谢谢!

4

2 回答 2

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];
}
于 2013-07-09T19:09:04.053 回答
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); 
于 2013-07-09T19:16:44.980 回答