xcode / iOS:自动调整以填充视图 - 显式帧大小是必不可少的?

时间:2011-02-07 11:33:15

标签: xcode ios uiview autoresize autoresizingmask

我希望UITextView填充superView,这是UIView个实例中的普通UIViewController

我似乎无法仅使用UITextViewautoresizingMask的API指定属性来autoresizesSubviews执行此操作。如此处所示设置这些没有任何作用;即使UITextView填满了屏幕,superView仍然很小。

// use existing instantiated view inside view controller;
// ensure autosizing enabled
self.view.autoresizesSubviews = YES;
self.view.autoresizingMask = UIViewAutoresizingFlexibleHeight|
                             UIViewAutoresizingFlexibleWidth;
// create textview
textView = [[[UITextView alloc] autorelease] initWithFrame:CGRectMake(0, 0, 1, 1)];
// enable textview autoresizing
[textView setAutoresizingMask:UIViewAutoresizingFlexibleWidth|
                              UIViewAutoresizingFlexibleHeight];
// add textview to view
[self.view addSubview:textView];

但是,如果我在视图控制器中实例化我自己的视图,替换它的'.view'属性,那么一切都按预期工作,并且textView填充其超级视图:

// reinstantiate view inside view controller
self.view = [[UIView alloc]init];
// create textview
textView = [[[UITextView alloc] autorelease] initWithFrame:CGRectMake(0, 0, 1, 1)];
// enable textview autoresizing
[textView setAutoresizingMask:UIViewAutoresizingFlexibleWidth|
                              UIViewAutoresizingFlexibleHeight];
// add textview to view
[self.view addSubview:textView];

我在所有这些初始化程序/方法中尝试了两个代码块,并且在每种情况下都会出现相同的情况:

-(id)init;
-(id)initWithFrame:(CGRect)frame;
-(void)viewDidLoad;

我意识到重新实现UIViewController的'.view'是非常难看的,任何人都可以解释我做错了什么吗?我假设我可以通过在UIViewController中使用初始框架设置代码来调整UITextView一次,然后autoresizing将根据需要运行来解决此问题。

-(void)viewDidLoad {
    textView.frame = self.view.frame;
}

...但是貌似view.frame没有在这个阶段设置,它没有定义'.size'值,所以textView再次保持小。

实现我想要的正确方法是什么?我必须通过UITextView:initWithFrame明确指定全屏维度才能让其填充超级视图吗?

我很感激您提出的任何建议。

2 个答案:

答案 0 :(得分:89)

自动调整并不意味着子视图将占用其超级视图的大小。它只是意味着只要superview的边界发生变化,它就会相对于superview的大小变化进行调整。因此,首先,您必须将子视图的大小设置为正确的值。然后,自动调整掩码将处理将来的大小更改。

这就是您所需要的:

textView = [[[UITextView alloc] autorelease] initWithFrame:self.view.bounds];
[textView setAutoresizingMask:UIViewAutoresizingFlexibleWidth|
                              UIViewAutoresizingFlexibleHeight];

答案 1 :(得分:0)

这里 Swift 3 解决方案:

myView.autoresizingMask = [.flexibleWidth, .flexibleHeight]