[Masonry] 实现原理及链式调用分析

本文介绍了Masonry布局框架的工作原理,包括它的轻量级特性、链式调用的DSL设计以及如何实现链式调用。此外,文章还探讨了Masonry与AutoLayout的关系,解释了为何使用Masonry可以简化布局代码,以及框架内部的关键类和方法,如MASConstraintMaker和MASViewConstraint。同时,文章提到了避免循环引用的方法,并提供了链式调用在实际开发中的应用示例。
摘要由CSDN通过智能技术生成

Masonry is a light-weight layout framework which wraps AutoLayout with a nicer syntax. Masonry has its own layout DSL which provides a chainable way of describing your NSLayoutConstraints which results in layout code that is more concise and readable. Masonry supports iOS and Mac OS X.

翻译:

Masonry是一个轻量级的布局框架,它使用更好的语法包装AutoLayout。 Masonry有自己的布局DSL,它提供了一种链式调用的方式来描述NSLayoutConstraints,从而使布局代码更简洁,更易读。 Masonry支持iOS和Mac OS X.

什么是DSL

DSL(Domain Specific Language) 翻译成中文就是:“领域特定语言”。首先,从定义就可以看出,DSL 也是一种编程语言,只不过它主要是用来处理某个特定领域的问题。

下边介绍iOS中如何实现链式调用的DSL。

为什么需要使用Masonry

首先看下直接用NSLayoutConstraints方式布局视图需要什么操作:

例如:我们需要布局一个视图view1,使他距离父视图上下左右都为10,NSLayoutConstraints布局代码如下:

公式:view1.top = superview.top * 1.0 + 10

UIView *superview = self.view;        UIView *view1 = [[UIView alloc] init];    view1.translatesAutoresizingMaskIntoConstraints = NO;    view1.backgroundColor = [UIColor greenColor];    [superview addSubview:view1];        UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10);        [superview addConstraints:@[                                //view1 constraints                                [NSLayoutConstraint constraintWithItem:view1                                                             attribute:NSLayoutAttributeTop                                                         relatedBy:NSLayoutRelationEqual                                                            toItem:superview                                                         attribute:NSLayoutAttributeTop                                                        multiplier:1.0                                                          constant:padding.top],                            [NSLayoutConstraint constraintWithItem:view1                                                         attribute:NSLayoutAttributeLeft                                                         relatedBy:NSLayoutRelationEqual                                                            toItem:superview                                                         attribute:NSLayoutAttributeLeft                                                        multiplier:1.0                                                          constant:padding.left],                            [NSLayoutConstraint constraintWithItem:view1                                                         attribute:NSLayoutAttributeBottom                                                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值