iOS屏幕变换的处理(1)

 

iOS屏幕变换,比如从竖屏转为横屏,虽然可以直接使用UIViewController的:

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)

 

但是,因为屏幕变换一般都要在视图(UIView)中处理,这种写法对视图并不方便。

也可以覆盖UIView的: - (void)layoutSubviews

 

在该方法中调整自身的frame属性。不过该方法应该是用于对自身的子视图做处理的方法:

    Subclasses can override this method as needed to perform more precise layout of their subviews. You should override this method only if the autoresizing behaviors of the subviews do not offer the behavior you want. You can use your implementation to set the frame rectangles of your subviews directly.

因此,也不适合。

 

实际上,如果屏幕的方向变化,系统会发出通知,只要注册通知,就可以正确处理屏幕的变换了。

首先,在需要变换的视图init方法注册通知:

- (id)initWithFrame:(CGRect)frame { 
    self = [super initWithFrame:frame]; 
    if (self) { 
        [[NSNotificationCenter defaultCenter] addObserver:self 
                                                 selector:@selector(changeFrames:) 
                                                     name:UIDeviceOrientationDidChangeNotification 
                                                   object:nil]; 
        self.backgroundColor=[UIColor greenColor]; 
    } 
    return self; 
}

 

然后,用如下方法处理通知到来的处理:

-(void)changeFrames:(NSNotification *)notification{
 
    NSLog(@"change notification: %@", notification.userInfo); 
    float width=[[UIScreen mainScreen]bounds].size.width*[[UIScreen mainScreen] scale]; 
    float height=[[UIScreen mainScreen]bounds].size.height*[[UIScreen mainScreen] scale]; 

    if ([[UIDevice currentDevice] orientation]==UIInterfaceOrientationPortrait 
        || [[UIDevice currentDevice] orientation]==UIInterfaceOrientationPortraitUpsideDown) { 
        NSLog(@">>>portrait"); 
        self.frame=CGRectMake(0, 0, height, width); 
    }
    else{ 
        NSLog(@">>>landscape"); 
        self.frame=CGRectMake(0, 0, width, height); 
    }

    NSLog(@"view—> %@",self); 
}

 

这里使用了:

float height=[[UIScreen mainScreen]bounds].size.height*[[UIScreen mainScreen] scale];

 

是因为,如果使用iPhone4,得到的[[UIScreen mainScreen]bounds].size.height值是480,还需要乘以它的缩放系数([[UIScreen mainScreen] scale])才是正确的值。

 

 

原文地址:http://marshal.easymorse.com/archives/4539

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值