如何为纵向和横向布局创建 UIView [英] How to create a UIView for both portrait and landscape layout

查看:30
本文介绍了如何为纵向和横向布局创建 UIView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个适用于纵向和横向模式的 UIView,但不确定如何实现这一点.仅供参考 - 我正在通过代码布置所有组件,因此没有 XIB 或故事板......这是必需的.

I am trying to create a UIView that will work for both portrait and landscape mode, but not sure how to achieve this. FYI - I am laying out all the components via code so no XIB or Storyboard... this is a requirement.

我有一个名为 createView 的方法,它列出了我在创建视图时调用的所有视图组件(按钮、标签等).

I have a method called createView that lays out all the view components (buttons, labels, etc...) which I call any time the view is created.

我不知道的是说我的控制器在水平模式下通过 addSubview:myNewCustomView 添加视图,那么从纵向切换时如何更改自定义 UIView 中的组件布局景观?

What I don't know is say my controller adds the view via addSubview:myNewCustomView while in horizontal mode, then how do I change the layout of the components in my custom UIView when switching from portrait to landscape?

我是否会在我的自定义 UIView 中创建方法,一个用于纵向布局,另一个用于横向布局?如果我有两种方法,我是否必须获得父显示模式,横向或纵向,然后在我的自定义 UIView 中调用适当的 createView 方法?

Would I create to methods in my custom UIView one to layout for portrait and another for landscape? If i have two methods, would I have to get the parents display mode, landscape or portrait, then call the appropriate createView method in my custom UIView?

推荐答案

您可以覆盖 CustomView 类中的 layoutSubviews 方法.在您的 ViewController 中,在您的 CustomView 对象上调用 setNeedsLayout.在您的自定义视图中保留一个方向变量

You can over-ride layoutSubviews method in your CustomView Class. And in your ViewController call setNeedsLayout on your CustomView Object. Keep a variable for orientation in your CustomView

在自定义视图中:-

- (void) layoutSubviews(){
    // set position and height width of the subviews according to this views params
}

在你的视图控制器中:-

In YourViewController:-

-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)orientation duration:(NSTimeInterval)duration {
    [yourCustomViewObj setOrientation:orientation];
    [yourCustomViewObj setNeedsLayout];
}

这篇关于如何为纵向和横向布局创建 UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆