iOS开发之进阶篇(12)—— 屏幕适配

iOS-Hero.png

目录:

  1. layoutSubviews
  2. Constrain to margins
  3. Constraints
  4. safeAreaLayoutGuide
  5. Masonry
  6. SnapKit

1. layoutSubviews

如果我们在viewDidLoad里加载一个view, 可能最终呈现的frame与我们所设置的不一致. 又或者我们旋转了屏幕, 界面没有被适配. 这些情况下, 我们就需要在layoutSubviews中重新指明frame布局.
为了验证调用顺序, 我们将重写viewController的self.view的layoutSubviews方法:

KKView.m

#import "KKView.h"

@implementation KKView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor redColor];
    }
    return self;
}

- (void)drawRect:(CGRect)rect {
    
    NSLog(@"%s", __func__);
}

- (void)layoutSubviews {
    
    NSLog(@"%s", __func__);
}

@end

viewController.m

#import "ViewController.h"
#import "KKView.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSLog(@"%s", __func__);
    
    KKView *aView = [[KKView alloc] initWithFrame:self.view.bounds];
    self.view = aView;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    NSLog(@"%s", __func__);
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    NSLog(@"%s", __func__);
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    
    NSLog(@"%s", __func__);
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    NSLog(@"%s", __func__);
}

@end

log:

2020-08-19 09:43:27.303328+0800 KKLayoutDemo[4069:80574] -[ViewController viewDidLoad]
2020-08-19 09:43:27.315342+0800 KKLayoutDemo[4069:80574] -[ViewController viewWillAppear:]
2020-08-19 09:43:27.320344+0800 KKLayoutDemo[4069:80574] -[ViewController viewWillLayoutSubviews]
2020-08-19 09:43:27.320512+0800 KKLayoutDemo[4069:80574] -[KKView layoutSubviews]
2020-08-19 09:43:27.320634+0800 KKLayoutDemo[4069:80574] -[ViewController viewDidLayoutSubviews]
2020-08-19 09:43:27.321131+0800 KKLayoutDemo[4069:80574] -[KKView drawRect:]
2020-08-19 09:43:27.361760+0800 KKLayoutDemo[4069:80574] -[ViewController viewDidAppear:]

在log顺序中, KKView的frame在layoutSubviews或者viewDidLayoutSubviews中确定. 其中layoutSubviewsUIView的方法, viewDidLayoutSubviewsUIViewController的方法.

如果我们使用代码或者xib来加载一个view, 那么最好在viewDidLayoutSubviews中重新设置一下frame, 而如果是storyboard加载的view, 则无需重新设置, 前提是设置了约束.

2. Constrain to margins

在使用storyboard布局的时候, 经常会看到Constrain to margins这个选项:

Constrain to margins = YES

它的作用是在子view上添加一个边界限制, 使其布局相对于父view有一个边距. 如图:

Constrain to margins = YES Effect

如果我们取消勾选, 使之上下左右约束为0, 则会铺满父视图.

Constrain to margins = NO.png
Constrain to margins = NO Effect.png

3. Constraints

Constraints约束决定了视图的frame布局, 然而我们可以在代码中动态修改Constraints的constant.
例如:

NSLayoutConstraint.png
centerYConstraint.png
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    self.centerYConstraint.constant = 100;  // Y 下调100
    
    NSLog(@"%s", __func__);
}


@property (readonly) CGFloat multiplier; // 比例只读, 不可调
@property CGFloat constant;

4. safeAreaLayoutGuide

iOS11之后UIView引入的一个新属性

@property(nonatomic,readonly,strong) UILayoutGuide *safeAreaLayoutGuide API_AVAILABLE(ios(11.0),tvos(11.0));

🌰

    CGRect rect;
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if (@available(iOS 11.0, *)) {
        rect = appDelegate.window.safeAreaLayoutGuide.layoutFrame;
    } else {
        rect = self.view.bounds;
    }
    
    KKView *aView = [[KKView alloc] initWithFrame:rect];
    [self.view addSubview:aView];
iPhone 8 & iPhone 11.png

5. Masonry

GitHub: https://github.com/SnapKit/Masonry

添加一个UIImageView, 设置边界:

#import "Masonry.h"

- (void)viewDidLoad {
    [super viewDidLoad];
       
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Catalina"]];
    [self.view addSubview:imageView];
    
    UIEdgeInsets padding = UIEdgeInsetsMake(20, 20, 20, 20);
    
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).with.insets(padding);
    }];
}

如果是刘海屏, 会有如下效果:

1.png

于是我们开始适配:

- (void)viewDidLoad {
    [super viewDidLoad];
        
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Catalina"]];
    [self.view addSubview:imageView];
    
    UIEdgeInsets padding = UIEdgeInsetsMake(20, 20, 20, 20);
    
//    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(self.view).with.insets(padding);
//    }];
    
    if (@available(iOS 11.0, *)) {

        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).with.offset(padding.top);
            make.left.equalTo(self.view.mas_safeAreaLayoutGuideLeft).with.offset(padding.left);
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).with.offset(-padding.bottom);
            make.right.equalTo(self.view.mas_safeAreaLayoutGuideRight).with.offset(-padding.right);
        }];

    } else {

        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_top).with.offset(padding.top);
            make.left.equalTo(self.view.mas_left).with.offset(padding.left);
            make.bottom.equalTo(self.view.mas_bottom).with.offset(-padding.bottom);
            make.right.equalTo(self.view.mas_right).with.offset(-padding.right);
        }];

    }
}

效果:

2.png

添加图片title:

    UILabel *label = [UILabel new];
    label.text = @"Catalina";
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor grayColor];
    [self.view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(imageView);
        make.right.equalTo(imageView);
        make.top.equalTo(imageView);
        make.height.equalTo(@50);
    }];
3.png

添加红绿蓝子view:

    UIView *redView = [UIView new];
    redView.backgroundColor = [UIColor redColor];
    [imageView addSubview:redView];
    
    UIView *greenView = [UIView new];
    greenView.backgroundColor = [UIColor greenColor];
    [imageView addSubview:greenView];
    
    UIView *blueView = [UIView new];
    blueView.backgroundColor = [UIColor blueColor];
    [imageView addSubview:blueView];
    
    [redView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(label.mas_bottom);
        make.bottom.equalTo(imageView);
        make.left.equalTo(imageView);
        make.width.equalTo(imageView).multipliedBy(1.0/3.0);
    }];
    
    [greenView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.and.width.equalTo(redView);
        make.left.equalTo(redView.mas_right);
    }];
    
    
    [blueView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.and.width.equalTo(greenView);
        make.left.equalTo(greenView.mas_right);
    }];
4.png

重新添加约束, 使红绿蓝竖排且高度相等:

    [redView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(label.mas_bottom);
        make.left.right.equalTo(imageView);
        make.bottom.equalTo(greenView.mas_top);
    }];

    [greenView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(imageView);
        make.bottom.equalTo(blueView.mas_top);
    }];
    
    [blueView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.and.bottom.equalTo(imageView);
        make.height.equalTo(@[redView, greenView]);
    }];
5.png

PS
mas_makeConstraints() 添加约束
mas_remakeConstraints() 移除之前的约束,重新添加新的约束
mas_updateConstraints() 更新约束,写哪条更新哪条,其他约束不变

equalTo() 参数是对象类型,一般是视图对象或者mas_width这样的坐标系对象
mas_equalTo() 和上面功能相同,参数可以传递基础数据类型对象,可以理解为比上面的API更强大

width() 用来表示宽度,例如代表view的宽度
mas_width() 用来获取宽度的值。和上面的区别在于,一个代表某个坐标系对象,一个用来获取坐标系对象的值

6. SnapKit

Masonry 的Swift 版本.
GitHub: https://github.com/SnapKit/SnapKit

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269