36

我想要一个UITextView来填充它的,这是一个实例superView中的一个平原。UIViewUIViewController

似乎我不能仅通过使用和UITextView的 API 指定属性来做到这一点。如此处所示设置这些没有任何作用;即使它填满了屏幕,它仍然很小。autoresizingMaskautoresizesSubviewsUITextViewsuperView

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

我意识到重新实例化 '.view' 是很糟糕的UIViewController,谁能解释我做错了什么?我认为我可以通过在我的初始框架设置代码中UIViewController调整UITextView一次大小来克服这个问题,然后autoresizing按照需要运行。

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

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

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

如果您能提供任何建议,我将不胜感激。

4

2 回答 2

89

自动调整大小并不意味着子视图将占用其父视图的大小。它只是意味着每当超级视图的边界发生变化时,它将相对于其超级视图的大小变化来调整大小。因此,最初,您必须将子视图的大小设置为正确的值。然后,自动调整大小的蒙版将处理未来的大小变化。

这就是你所需要的:

textView = [[[UITextView alloc] autorelease] initWithFrame:self.view.bounds];
[textView setAutoresizingMask:UIViewAutoresizingFlexibleWidth|
                              UIViewAutoresizingFlexibleHeight];
于 2011-02-07T12:35:27.797 回答
0

这里是 Swift 3解决方案:

myView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
于 2017-04-19T08:06:06.757 回答