以编程方式布局 iPhone UIView?
我在 Linux 上使用 iPhone 工具链,因此没有 Interface Builder。那么如何在 ViewController 子类中布局视图呢?比如我想要一个UITextView在屏幕中间?我应该在 loadView
或 viewDidLoad
中执行此操作吗?我是否还必须将 ViewController 子类的视图设置为其自身?
I am using the iPhone toolchain on Linux and so I have no Interface Builder. So how could I layout my view in my ViewController subclass? For example, I want a UITextView in the middle of the screen? Should I do this in the loadView
or viewDidLoad
. Do I also have to set the view for the ViewController subclass to itself?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用代码来布局所有视图并不是一件容易的事。以下是一些代码:
框架是位置(第一个和第二个参数是 x 和 y 协调器)和大小(第三个和第四个参数是文本视图的宽度和高度)。
使用这种方式,您可以将任何视图添加到您的类中。有些视图是内置的,你不必自己绘制,有些则不是,你需要子类化 UIView 并重写drawRect。
当主视图控制器完成加载时,您应该在 viewDidLoad 中执行此操作
It is not an easy job to layout all the view using code. Here are some code:
The frame is the place (the first and second argument is x and y coordinator) and the size (the third and fourth argument is width and height of the text view).
Using this way, you can add any view into your class. Some of the view is built in and you don't have to draw yourself, some of them is not, and you need to subclass UIView and override drawRect.
You should do this in viewDidLoad when your main view controller is finished loading
我编写了一个开源项目,它正是这样做的:
https://github.com/charlesmchen/WeViews
这是另一个您可能会觉得有用的项目:
http://code.google.com/p/layoutmanagers/
I've written an open source project that does exactly this:
https://github.com/charlesmchen/WeViews
Here's another project that you might find useful:
http://code.google.com/p/layoutmanagers/
我通常在 loadView 方法中构建整个视图层次结构,并在 viewDidLoad 中执行其他设置,例如设置子视图内容以反映与视图控制器关联的数据。重要的是在 loadView 方法中设置视图控制器 view 出口。
最大的困难可能是理解 IB 设置如何映射到 UIView 变量和方法,例如自动调整大小掩码。 Apple 的 UIView 和 UIViewController 类参考充满了有用的信息。
I usually build the entire view hierarchy in the loadView method and perform additional setup in the viewDidLoad, for example to set up the subviews content to reflect the data associated to the view controller. The important thing is to set the view controller view outlet in the loadView method.
The biggest difficulty is probably understanding how IB settings map to UIView variables and methods, for example the autoresizing mask. Apple's UIView and UIViewController class references are full of useful informations.