簡體   English   中英

iOS:如何使兩個UIViews自動填充空間?

[英]iOS: How do you make two UIViews auto fill space?

我試圖以編程方式使兩個視圖共享父視圖的寬度。 我嘗試過使用一個用於子視圖的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];

謝謝!

您從未設置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];
}

嘗試設置添加到主視圖的子視圖的一些初始框架。 這應該有助於:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM