objective-c - 如何检测以编程方式生成的 UIView 的旋转

标签 objective-c ios uiview rotation

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

- (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;
}

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

最佳答案

您可以让设备开始生成旋转通知:

  [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

添加您自己的选择器作为设备旋转通知的观察者:

      [[NSNotificationCenter defaultCenter] addObserver: self selector:   @selector(deviceOrientationDidChange:) name: UIDeviceOrientationDidChangeNotification object: nil];

然后编写你的通知处理程序

- (void)deviceOrientationDidChange:(NSNotification *)notification {
     //Obtain current device orientation
     UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

      //Do my thing
 }

请记住在调用自定义 UIView 的 dealloc 方法时(或完成时)移除观察者,并停止生成设备更改通知。

-(void) dealloc{
[[NSNotificationCenter defaultCenter] removeObserver: self];
[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
}

这对您的问题有帮助吗?

关于objective-c - 如何检测以编程方式生成的 UIView 的旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12126098/

相关文章:

iPhone iOS如何实例化一个黑白CGColorSpaceRef?

ios - 如何让 UILabel 在单词末尾显示 "..."而不是截断它?

ios - 按需隐藏底栏

iphone - 更改 uisegmentedcontrol 中选定段的字体

ios - 使用 unwind segue 将数据发送回之前的 Controller ?

objective-c - #include <new> 未找到,但仅当从特定 header 引用该文件时?

ios - 启动屏幕旋转不适用于 iPhone 6s 和更小的屏幕

iphone - 在应用程序版本等之间访问 CoreData 实体

ios - 无法识别 ReachabilityManager 单例类方法

ios - 绘制中 uibezierpath 上的阴影设置(矩形 :) removed when view is redrawn