标签:
因为本来不喜欢使用StoryBoard、xib等可视化编程,一直使用的纯代码布局,但是纯代码布局的iOS开发者会遇到一个问题,就是横竖屏适配的问题,如果使用自动布局,那些约束的,写起来都是不难,但是控件之间的关联太多,以至于维护性很差。本人由于工作的原因,做iPad开发,那就必须要解决横竖屏适配的问题,于是就有了这篇文章。
代码如下:
//
// ViewController.swift
// iPad横竖屏切换
//
// Created by zhangxu on 16/7/30.
// Copyright © 2016年 zhangxu. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
private var leftView : UIView!;
private var topView : UIView!;
private var rightView : UIView!;
private var bottomView : UIView!;
private var viewW : CGFloat = kScreenWidth;
private var viewH : CGFloat = kScreenHeight;
// MARK: - 视图加载完毕调用此方法
override func viewDidLoad() {
super.viewDidLoad()
topView = UIView();
topView.backgroundColor = UIColor.redColor();
self.view.addSubview(topView);
leftView = UIView();
leftView.backgroundColor = UIColor.blueColor();
self.view.addSubview(leftView);
rightView = UIView();
rightView.backgroundColor = UIColor.purpleColor();
self.view.addSubview(rightView);
bottomView = UIView();
bottomView.backgroundColor = UIColor.brownColor();
self.view.addSubview(bottomView);
// Do any additional setup after loading the view, typically from a nib.
}
// MARK: - 支持视图旋转
override func shouldAutorotate() -> Bool {
return true;
}
// MARK: - 交换两个数的值
func changeValue(value1 : CGFloat , value2 : CGFloat) -> (temp1 : CGFloat , temp2 : CGFloat) {
return (value2 , value1);
}
// MARK: - 当前视图将要旋转到的方向
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
if toInterfaceOrientation.isPortrait {
print("Portrait");
(viewW , viewH) = changeValue(viewW, value2: viewH);
self.view.layoutIfNeeded();
} else if toInterfaceOrientation.isLandscape {
print("Landscape");
(viewW , viewH) = changeValue(viewW, value2: viewH);
self.view.layoutIfNeeded();
}
}
// MARK: - 设置子控件的frame
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews();
let topViewX = RealValue(0);
let topViewY = RealValue(0);
let topViewW = viewW;
let topViewH = RealValue(49);
topView.frame = CGRectMake(topViewX, topViewY, topViewW, topViewH);
let leftViewX = topViewX;
let leftViewY = CGRectGetMaxY(topView.frame);
let leftViewW = RealValue(250);
let leftViewH = viewH - topViewH;
leftView.frame = CGRectMake(leftViewX, leftViewY, leftViewW, leftViewH);
let rightViewX = leftViewW;
let rightViewY = topViewH;
let rightViewW = viewW - leftViewW;
let rightViewH = viewH - topViewH * 2;
rightView.frame = CGRectMake(rightViewX, rightViewY, rightViewW, rightViewH);
let bottomViewX = leftViewW;
let bottomViewY = CGRectGetMaxY(rightView.frame);
let bottomViewW = viewW - leftViewW;
let bottomViewH = topViewH;
bottomView.frame = CGRectMake(bottomViewX, bottomViewY, bottomViewW, bottomViewH);
}
// MARK: - 发生内存警告调用此方法
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
如果觉得看的不过瘾,这里有demo
标签:
原文地址:http://www.cnblogs.com/Brisy/p/5721329.html