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

Kom*_*ave 36 xcode uiview autoresize ios autoresizingmask

UITextView想要填充它superView,这是UIView一个UIViewController实例内的平原.

看来,我不能让UITextView这样做完全由使用的API指定的性质autoresizingMaskautoresizesSubviews.如此处所示设置这些没有任何作用; 在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];
Run Code Online (Sandbox Code Playgroud)

但是,如果我在视图控制器中实例化我自己的视图,替换它的'.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];
Run Code Online (Sandbox Code Playgroud)

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

-(id)init;
-(id)initWithFrame:(CGRect)frame;
-(void)viewDidLoad;
Run Code Online (Sandbox Code Playgroud)

我意识到重新UIViewController复制'.view'是非常难看的,任何人都可以解释我做错了吗?我假设我可以通过在我的内容中设置初始帧设置代码UIViewController来解决问题UITextView,然后autoresizing根据需要进行操作.

-(void)viewDidLoad {
    textView.frame = self.view.frame;
}
Run Code Online (Sandbox Code Playgroud)

...但是貌似view.frame没有在这个阶段设置,它没有定义'.size'值,所以textView仍然很小.

实现我想要的正确方法是什么?我必须明确指定全屏尺寸,UITextView:initWithFrame以使其填充其超级视图吗?

我很感激您提供的任何建议.

Ole*_*ann 89

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

这就是你所需要的:

textView = [[[UITextView alloc] autorelease] initWithFrame:self.view.bounds];
[textView setAutoresizingMask:UIViewAutoresizingFlexibleWidth|
                              UIViewAutoresizingFlexibleHeight];
Run Code Online (Sandbox Code Playgroud)