关于UIView的横竖屏自适应

来源:互联网 发布:淘宝购物业务流程图 编辑:程序博客网 时间:2024/05/15 23:45

本文的属性也不知道是原创还是摘抄了,一个同事正在学横竖屏自适应的东西,刚看到用代码调整的部分,然后我徒手给实现了用IB实现的方式,估计书上应该都有,只是我没看吧。
简单来说就两种方式:代码实现和IB实现
原理都是通过判断方向旋转然后给出相应的调整方式。
效果图:


代码实现:
ViewController.h

@property (nonatomic,retain)IBOutlet UIButton *button1;
@property (nonatomic,retain)IBOutlet UIButton *button2;
@property (nonatomic,retain)IBOutlet UIButton *button3;
@property (nonatomic,retain)IBOutlet UIButton *button4;
@property (nonatomic,retain)IBOutlet UIButton *button5;
@property (nonatomic,retain)IBOutlet UIButton *button6;

做几个连接变量,要和界面上对应的按钮连接起来
ViewController.h

-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation 
                                        duration:(NSTimeInterval)duration{
  if (toInterfaceOrientation == UIInterfaceOrientationPortrait ||toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
    button1.frame = CGRectMake(20, 20, 125, 125);
    button2.frame = CGRectMake(175, 20, 125, 125);
    button3.frame = CGRectMake(20, 168, 125, 125);
    button4.frame = CGRectMake(175, 168, 125, 125);
    button5.frame = CGRectMake(20, 315, 125, 125);
    button6.frame = CGRectMake(175, 315, 125, 125);
  }else{
    button1.frame = CGRectMake(20, 20, 125, 125);
    button2.frame = CGRectMake(20, 155, 125, 125);
    button3.frame = CGRectMake(177, 20, 125, 125);
    button4.frame = CGRectMake(177, 155, 125, 125);
    button5.frame = CGRectMake(328, 20, 125, 125);
    button6.frame = CGRectMake(328, 155, 125, 125);
  }
}

增加一个方向适应函数。我觉得最麻烦的就是这个代码调位置,然后就齐活了。
IB实现:
ViewController.xib

实现两个View,分别对应横屏和竖屏
ViewController.h

@interface ViewController : UIViewController{
    IBOutlet UIView *protView;
    IBOutlet UIView *landView;
}

增加两个连接变量,分别对应横屏和竖屏
ViewController.m

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
    // Return YES for supported orientations
    if (interfaceOrientation == UIInterfaceOrientationPortrait ||
        interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown ) {
        self.view = protView;
    }
    else{
        self.view = landView;
    }
    return YES;
}

当方向改变时自动选择对应的view,that’s all!

讨论:对于使用哪种方式,笔者还是倾向使用IB,虽然用代码的方式看起来比较酷,也有代码控说这样写着比较爽。我想说的的,面对复杂的应用环境,需求天天变,界面天天调,如果用代码的话,死的心都会有的。再说MVC这么酷的框架干嘛不用?

源代码下载:
AutosizeCode
AutosizeView

原创粉丝点击