Xcode/iOS:自动调整大小以填充视图 - 显式框架大小是必要的吗?

37

我想让一个UITextView填满它的superView,这个superView是一个普通的UIView,位于UIViewController实例中。

使用API指定的autoresizingMaskautoresizesSubviews属性似乎无法使UITextView做到这一点。即使按照此处所示进行设置,它也无济于事;尽管其superView填满屏幕,但UITextView仍然很小。

// 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明确指定全屏尺寸才能使其填充其父视图吗?

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


1
init之前不要使用autorelease。正确的顺序是...alloc] init] autorelease]UIView应该没问题,但如果你在错误的顺序中使用autoreleaseinitNSString和其他类簇将会泄漏。很抱歉无法帮助你的真正问题。 - Yuji
1
谢谢Yuji,我很感激这个提示——这是我之前不知道的东西! - KomodoDave
2个回答

90

Autoresizing并不意味着子视图会占用其父视图的大小。它只是意味着每当父视图的边界改变时,子视图会相对地调整大小。因此,最初您需要将子视图的大小设置为正确的值。自动调整大小掩码将处理未来的大小更改。

这就是你所需要的:

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

1
我将这个放入loadView中(确保首先调用[super loadView]),它可以很好地完成工作 :) 非常感谢,Ole - KomodoDave
对于Swift,它看起来像这样:var textView = UITextView(frame: self.view.bounds) textView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight - martinmose
1
对于Swift 2,请使用以下代码:textView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight] - Peter Kreinz

0

这里是Swift 3的解决方案:

myView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接