我有一个UIButton,我实现编程,因为它只需要当我旋转设备
按钮需要在旋转时消失,横向时出现
只要我留在同一个ViewController我没有问题。我可以以任何方式旋转设备,按钮会像预期的那样出现和消失。这个应用是一个基于TabController的应用,当我转到另一个标签时,同样的行为会发生。
这就是问题所在当我回到原始视图时,按钮出现了,但之后就再也没有消失。这几乎就像没有调用removeFromSuperView
,但即使它被调用,按钮也不会被删除。
知道这是为什么吗?
-(void)autoRotationDetection
{
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter]
addObserver:self selector:@selector(orientationChanged:)
name:UIDeviceOrientationDidChangeNotification
object:[UIDevice currentDevice]];
}
- (void) orientationChanged:(NSNotification *)note
{
UIDevice * device = note.object;
switch(device.orientation)
{
case UIDeviceOrientationPortrait:
/* start special animation */
[_menuButton removeFromSuperview];
break;
case UIDeviceOrientationPortraitUpsideDown:
/* start special animation */
break;
default:
break;
};
}
然后我调用
-(void)viewWillAppear:(BOOL)animated
{
[self autoRotationDetection];
}
对不起,我应该加上这句
我看到过这种行为(行为不同后去另一个标签,并再次回来)当调用[super viewWillAppear]被遗漏。试着添加它,看看是否能修复它。
编辑后:
我认为一个更简单的方法是在viewWillLayoutSubviews中查看视图的边界,它在每次旋转时被调用(以及其他时间,但对于像这样简单的事情,那不应该重要)。在这个例子中,我隐藏或显示而不是删除,但这个概念应该适用于两者。
-(void)viewWillLayoutSubviews {
BOOL portrait = self.view.bounds.size.height > self.view.bounds.size.width;
if (portrait) {
self.button.hidden = YES;
}else{
self.button.hidden = NO;
}
}
您可以通过跟踪上次调用该方法时portrait的值来提高效率,并且仅在portrait发生变化时才更改按钮的状态