xcode/iOS : Autoresize to fill a view - explicit frame size is essential?

标签 xcode ios uiview autoresize autoresizingmask

我想要一个 UITextView 来填充它的 superView,它是 UIViewController 实例中的普通 UIView .

我似乎无法让 UITextView 仅通过使用 autoresizingMaskautoresizesSubviews 的 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/

相关文章:

ios - 无需委托(delegate)即可获取 UITextView 文本

iOS 从 View 中添加/删除阴影

ios - 如何添加一个覆盖所有其他 View (包括导航栏和状态栏)的黑屏?

xcode - 替换 :make command with a custom script in vim

ios - 更改 "More"选项卡的 UINavigationbar 颜色?

php - 为什么 Parse 类不保存?

ios - AutoLayout以编程方式导致iPhone 4中出现问题

ios - 在 Xcode 4.5 之后使用 instruments 跟踪 Core Animation 性能

ios - Swift 3 - 尝试执行获取请求时程序崩溃

ios - 在 UIScrollView 中滚动和缩放 UIImageView