我有一个以编程方式创建的 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/