0

我有一个扩展 UIViewController 的 GUI 类。

在它的功能viewDidLoad中,我想有一个UITextField实例。我希望该实例不作为一个简单的 CGRect 对齐,设置它的偏移量和宽度和高度,但我希望它动态调整大小,使其填充屏幕的整个宽度,从顶部、左侧和左侧偏移 5px正确的每个和 20px 的高度。这是怎么做的?

无论设备方向如何,它都应保持“相对绝对”的定位,支持所有方向。

也许有类似 LayoutManager 的东西,例如 Java 中的 GridBagLayout?

4

3 回答 3

2

您要设置autoresizingMask视图的属性。

UIView *theParentView; // Assume this is the root view that owns the whole screen

CGRect textFieldFrame = CGRectMake(5, // Top-left corner x position
                                   5, // Top-left corner y position
                                   [theParentView bounds].width - 10, // Width
                                   20); // Height

UIView *myView = [[UIView alloc] initWithFrame:textFieldFrame];

// This will make it resize with the parent view, maintaining margins
[myView setAutoresizingMask:UIViewAutoresizingFlexibleWidth];

[theParentView addSubview:myView];

[myView release];

这也可以从 Interface Builder 完成。甚至还有一个小动画展示了如何在 Interface Builder 中调整视图的大小。

于 2011-06-03T19:52:37.617 回答
1

请记住,UIViewController 本身不会显示,但它管理视图对象的层次结构。您可以在 -viewDidLoad 中创建文本字段,但需要将其添加到视图控制器的视图中才能看到它。你会做这样的事情:

CGFloat inset = 5.0;
CGFloat fieldHeight = 20.0;
CGRect fieldRect = CGRectMake(inset,
                              inset,
                              self.view.size.width - (2 * inset),
                              fieldHeight);
UITextField *field = [[UITextField alloc] initWithFrame:fieldRect];
field.autoResizingMask = UIViewAutoresizingFlexibleWidth;
[self.view addSubview:field];
[field release];

当然,如果您稍后需要再次引用该字段,您还需要将指向它的指针存储在属性或 ivar 中。

于 2011-06-03T19:53:18.227 回答
-1

操作系统中没有内置任何东西。我已经看到了几个版本,比如你在问什么,包括我自己的,它在GitHub 上

于 2011-06-03T19:52:34.917 回答