如何检测以编程方式生成的UIView的旋转 [英] How to detect rotation for a programatically generated UIView

查看:122
本文介绍了如何检测以编程方式生成的UIView的旋转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以编程方式创建的 UIView

I have a UIView that's programmatically being created:

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    if (self) {
        self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.5];

        UIImageView* closeButton = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"modal_close.png"]];

        closeButton.frame = CGRectMake(self.frame.size.width*.89, self.frame.size.height*.09, closeButton.frame.size.width, closeButton.frame.size.height);

        UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(self.frame.size.width*.89, self.frame.size.height*.09,20, 20)];

        [button addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];

        UIView* mainView = [[UIView alloc] initWithFrame:CGRectMake(self.frame.size.width*.1,self.frame.size.height*.1,self.frame.size.width*.8,self.frame.size.height*.8)];

        mainView.backgroundColor = [UIColor whiteColor];
        _displayMainView = mainView;        

        [self addSubview:_displayMainView];
        [self addSubview:closeButton];
        [self addSubview:button];

        mainView = nil;
        closeButton = nil;
    }
    return self;
}

如何检测旋转?这是作为另一个现有视图之上的模态。这是一个仅限iPad的应用程序,如果这很重要。

How can I detect rotation? This is to act as a modal on top of another existing view. This is an iPad only app, if that matters.

推荐答案

我认为你有两个选择:


  1. 您将视图置于自定义 UIViewController 并覆盖 shouldAutorotateToInterfaceOrientation:方法,为所有你想要支持的方向。视图控制器将自动旋转并调整内容大小(您的视图)。您只需确保拥有正确的autoresizeMask(或约束,如果您使用autolayout)。

  2. 您可以直接观察加速度计对设备方向的更改。然后你可以在需要时调整你的视图。

  1. You put the view in a custom UIViewController and override the shouldAutorotateToInterfaceOrientation: method to return YES for all the orientations you want to support. The view controller will automatically rotate and resize the content (your view). You just have to make sure to have the correct autoresizeMask (or constrains, if you're using autolayout).
  2. You directly observe changes to the devices orientation with the accelerometer. Then you can adjust your view when needed.

如果可以的话,这是你应该选择的第一种方法。

It's really the first approach you should choose if you can.

这篇关于如何检测以编程方式生成的UIView的旋转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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