我想要一个 UITextView
来填充它的 superView
,它是 UIViewController
实例中的普通 UIView
.
我似乎无法让 UITextView
仅通过使用 autoresizingMask
和 autoresizesSubviews
的 API 指定属性来执行此操作。如此处所示设置这些不会执行任何操作; 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 Controller 中实例化我自己的 View ,替换它的“.view”属性,那么一切都按预期工作,并且 textView 填充它的 super View :
// 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
明确指定全屏尺寸以使其填充其 super View ?
如果您能提供任何建议,我将不胜感激。
最佳答案
Autoresizing 并不意味着 subview 将占用其父 View 的大小。这只是意味着每当父 View 的边界发生变化时,它将根据其父 View 的大小变化来调整大小。所以最初,您必须将 subview 的大小设置为正确的值。自动调整掩码将处理 future 的尺寸变化。
这就是您所需要的:
textView = [[[UITextView alloc] autorelease] initWithFrame:self.view.bounds];
[textView setAutoresizingMask:UIViewAutoresizingFlexibleWidth|
UIViewAutoresizingFlexibleHeight];
关于xcode/iOS : Autoresize to fill a view - explicit frame size is essential?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4920798/