草庐IT

iOS Masonry布局(一)

FieryDragon 2023-09-21 原文

Masonry是项目中常见的自动布局库,采用链式语法封装。

常见布局方法

1.添加约束

- (NSArray *)mas_makeConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *make))block;

2.更新约束

- (NSArray *)mas_updateConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *make))block;

3.删除以前的约束,重新约束

- (NSArray *)mas_remakeConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *make))block;

添加约束前需将试图添加到父试图,否则将引起崩溃

等间距布局

适合固定视图,内部没有清空原有视图的布局,所以数组内视图变动后再调用该方法更新布局会引起UI异常。

/**
 *  distribute with fixed spacing
 *
 *  @param axisType     横向排列或竖行排列
 *  @param fixedSpacing 视图间隔大小
 *  @param leadSpacing  第一个视图距边缘间隔大小
 *  @param tailSpacing  最后一个视图距边缘间隔大小
 */
- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType
                    withFixedSpacing:(CGFloat)fixedSpacing
                         leadSpacing:(CGFloat)leadSpacing
                         tailSpacing:(CGFloat)tailSpacing

示例:

    NSArray *arrays = @[redView,blueView,yellowView,brownView];
    
    [arrays mas_distributeViewsAlongAxis:MASAxisTypeHorizontal
                        withFixedSpacing:10.f
                             leadSpacing:30.f
                             tailSpacing:30.f];
    [arrays mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(150.f);
        make.height.mas_equalTo(50.f);
    }];
等间距.png
等宽布局

适合固定视图,内部没有清空原有视图的布局,所以数组内视图变动后再调用该方法更新布局会引起UI异常。

/**
 *  distribute with fixed item size
 *
 *  @param axisType        横向排列或竖行排列
 *  @param fixedItemLength 视图宽或高
 *  @param leadSpacing     第一个视图距边缘间隔大小
 *  @param tailSpacing     最后一个视图距边缘间隔大小
 */
- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedItemLength:(CGFloat)fixedItemLength leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing;

示例:

    [arrays mas_distributeViewsAlongAxis:MASAxisTypeHorizontal
                     withFixedItemLength:75.f
                             leadSpacing:30.f
                             tailSpacing:30.f];
    [arrays mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(150.f);
        make.height.mas_equalTo(50.f);
    }];
等宽.png
间隔布局 - offset

offset常用于设置两个视图边缘的间隔,同时可以在布局完成后动态的改动视图间的间隔大小。

示例:视图左侧相距页面左边缘20像素。

@property (nonatomic, strong) MASConstraint *redViewLeftConstraint;

#pragma mark - 布局
    [redView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(130.f);
        _redViewLeftConstraint = make.left.equalTo(self.view.mas_left).offset(20.f);
        make.width.mas_equalTo(180.f);
        make.height.mas_equalTo(90.f);
    }];
左布局.png

改变视图左间距(此时间距值会直接覆盖上次设置的间隔大小,不会累加)。

    _redViewLeftConstraint.offset(100.f);
offset.png

示例:视图右侧相距页面右边缘20像素。

@property (nonatomic, strong) MASConstraint *redViewRightConstraint;

#pragma mark - 布局
    [redView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(130.f);
        _redViewRightConstraint = make.right.equalTo(self.view.mas_right).offset(-20.f);
        make.width.mas_equalTo(180.f);
        make.height.mas_equalTo(90.f);
    }];
右布局.png

改变视图间距

    _redViewRightConstraint.offset(-100.f);
offsetR.png

结论:第二个视图相对第一个视图右移时offset(正数),第二个视图相对第一个视图左移时offset(负数)

equalTo与mas_equalTo区别

equalTo(value)等于value值。

    [redView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(130.f);
        make.left.equalTo(self.view.mas_left).offset(20.f);
        make.width.mas_equalTo(180.f);
        make.height.mas_equalTo(90.f);
    }];
    redView.text = @"redViewredView";
redViewredView.png
    redView.text = @"redViewredViewredViewredView";
redViewredViewredViewredView.png

如图所示:视图宽度固定180像素,不会因内容的改变而改变。

  • 区别
#define mas_equalTo(...)                 equalTo(MASBoxValue((__VA_ARGS__)))
#define mas_greaterThanOrEqualTo(...)    greaterThanOrEqualTo(MASBoxValue((__VA_ARGS__)))
#define mas_lessThanOrEqualTo(...)       lessThanOrEqualTo(MASBoxValue((__VA_ARGS__)))

#define mas_offset(...)                  valueOffset(MASBoxValue((__VA_ARGS__)))

mas_equalTo只是对其参数进行了一个BOX(装箱) 操作,目前支持的类型:数值类型(NSNumber)、 点(CGPoint)、大小(CGSize)、边距(UIEdgeInsets),而equalTo这个方法不会对参数进行包装。

lessThanOrEqualTo

lessThanOrEqualTo(value)少于或等于value值,常用于内容可能动态改变情况。

示例:宽度少于等于180像素。

    [redView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(130.f);
        make.left.equalTo(self.view.mas_left).offset(20.f);
        make.width.mas_lessThanOrEqualTo(180.f);
        make.height.mas_equalTo(90.f);
    }];
    redView.text = @"redView";
redView.png
    redView.text = @"redViewredViewredView";
redViewredViewredView.png

如图所示,视图宽度会随着内容动态改变,但是最大不超过180像素,超出内容省略展示。

示例:此处红色视图右边缘距父视图右边缘间隔大于20像素,但是上节中介绍第二个视图相对第一个视图左移时offset(负数),故此处使用lessThanOrEqualTo。

    [redView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(130.f);
        make.left.equalTo(self.view.mas_left).offset(20.f);
        make.right.lessThanOrEqualTo(self.view.mas_right).offset(-20.f);
        make.width.mas_equalTo(180.f);
        make.height.mas_equalTo(90.f);
    }];
    redView.text = @"redViewredView";
lessThanOrEqualTo.png
greaterThanOrEqualTo

greaterThanOrEqualTo(value)大于或等于value值。

示例:宽度大于等于180像素。

    [redView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(130.f);
        make.left.equalTo(self.view.mas_left).offset(20.f);
        make.width.mas_greaterThanOrEqualTo(180.f);
        make.height.mas_equalTo(90.f);
    }];
    redView.text = @"redView";
greaterThanOrEqualTo.png
    redView.text = @"redViewredViewredViewredViewredView";
redViewredViewredViewredViewredView.png

如图所示:宽度随着文字的内容改变,但即使文字较少时宽度也不会小于180像素。

比例布局 - multipliedBy、dividedBy

multipliedBy:属性表示约束值为约束对象的乘因数。
dividedBy:属性表示约束值为约束对象的除因数。

示例:红色视图宽180高90,蓝色视图宽180高为宽度的0.5倍数。

    [redView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(130.f);
        make.left.equalTo(self.view.mas_left).offset(20.f);
        make.width.mas_equalTo(180.f);
        make.height.mas_equalTo(90.f);
    }];
    [blueView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(130.f);
        make.right.equalTo(self.view.mas_right).offset(-20.f);;
        make.width.mas_equalTo(180.f);
        make.height.equalTo(blueView.mas_width).multipliedBy(0.5);
    }];
multipliedBy.png

通过图片可知两个视图高度相同,而蓝色视图0.5倍宽度的高度值正是90。

快速定位约束冲突视图 - mas_key

Masonry可以通过给视图控件设置key值来区分不同的控件,方便出现约束冲突时快速定位到有约束冲突的视图。
示例:

    [redView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(130.f);
        make.left.equalTo(self.view.mas_left).offset(20.f);
        make.right.equalTo(self.view.mas_right).offset(-20.f);
        make.width.mas_equalTo(180.f);
        make.height.mas_equalTo(90.f);
    }];

控制台会提示约束冲突日志如下:

[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<MASLayoutConstraint:0x6000036ea580 UIView:0x7fcbfe4022f0.left == UIView:0x7fcbfe607e10.left + 20>",
    "<MASLayoutConstraint:0x6000036ea5e0 UIView:0x7fcbfe4022f0.right == UIView:0x7fcbfe607e10.right - 20>",
    "<MASLayoutConstraint:0x6000036e9ec0 UIView:0x7fcbfe4022f0.width == 180>",
    "<NSLayoutConstraint:0x6000031caad0 UIView:0x7fcbfe607e10.width == 414>"
)

Will attempt to recover by breaking constraint 
<MASLayoutConstraint:0x6000036e9ec0 UIView:0x7fcbfe4022f0.width == 180>

当应用中布局比较多或者布局比较相似时想快速准确定位到有冲突的视图比较困难。

    redView.mas_key = @"redViewKey";
    [redView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(130.f);
        make.left.equalTo(self.view.mas_left).offset(20.f);
        make.right.equalTo(self.view.mas_right).offset(-20.f);
        make.width.mas_equalTo(180.f);
        make.height.mas_equalTo(90.f);
    }];
[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<MASLayoutConstraint:0x6000001ec6c0 UIView:redViewKey.left == UIView:0x7fe3b6602b00.left + 20>",
    "<MASLayoutConstraint:0x6000001ec1e0 UIView:redViewKey.right == UIView:0x7fe3b6602b00.right - 20>",
    "<MASLayoutConstraint:0x6000001ec720 UIView:redViewKey.width == 180>",
    "<NSLayoutConstraint:0x6000006d0910 UIView:0x7fe3b6602b00.width == 414>"
)

Will attempt to recover by breaking constraint 
<MASLayoutConstraint:0x6000001ec720 UIView:redViewKey.width == 180>

对比设置mas_key前后的冲突日志可以发现,设置后日志会直接显示冲突视图的key值(UIView:redViewKey.right == ...),这样我们就能快速准确的定位到约束冲突视图。

优先级 - priority

每个约束都有一个优先级,优先级的范围是1 ~ 1000,默认创建的约束优先级是MASLayoutPriorityRequired(1000)。
作用:优先实现优先级高的设置,发生冲突时,放弃优先级低的设置。

常见优先级设置:

  • .priority() 设定一个明确的优先级的值。
  • .priorityHigh() 无参数,使用预设的MASLayoutPriorityDefaultHigh(750)值。
  • .priorityMedium(),使用默认的MASLayoutPriorityDefaultMedium(500)值。
  • .priorityLow(),使用默认的MASLayoutPriorityDefaultLow(250)值。

如上节中约束冲突可以通过设置优先级解决:

    [redView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(130.f);
        make.left.equalTo(self.view.mas_left).offset(20.f).priorityHigh();
        make.right.equalTo(self.view.mas_right).offset(-20.f).priority(740);
        make.width.mas_equalTo(180.f);
        make.height.mas_equalTo(90.f);
    }];
优先级.png

priorityHigh()优先级高于priority(740),故make.left.equalTo(self.view.mas_left).offset(20.f).priorityHigh()生效,结果如图所示。

单个约束的生效与删除 - uninstall、install

install:约束生效。
uninstall:约束删除。
示例:

@property (nonatomic, strong) MASConstraint *redViewLeftConstraint;
@property (nonatomic, strong) MASConstraint *redViewRightConstraint;

#pragma mark - 布局
[redView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(130.f);
        _redViewLeftConstraint = make.left.equalTo(self.view.mas_left).offset(20.f).priorityHigh();
        _redViewRightConstraint = make.right.equalTo(self.view.mas_right).offset(-20.f).priority(740);
        make.width.mas_equalTo(180.f);
        make.height.mas_equalTo(90.f);
    }];

#pragma mark - 更改约束
[_redViewLeftConstraint uninstall];
[_redViewRightConstraint install];

install.png

如图所示:使用install、uninstall更改约束后,视图变为距右边缘20像素。

提高可读性 - with、and
- (MASConstraint *)with {
    return self;
}

- (MASConstraint *)and {
    return self;
}

查看方法代码可知两个方法没有做任何操作,只是返回对象本身,两个方法的作用是为了提高可读性。

动画
    _redViewRightConstraint.offset(-100.f);
    
    //告知需要更新约束,但不会立刻开始,系统然后调用updateConstraints
    [self.view setNeedsUpdateConstraints];
    //告知立刻更新约束,系统立即调用updateConstraints
    [self.view  updateConstraintsIfNeeded];
    [UIView animateWithDuration:0.4 animations:^{
        //告知页面立刻刷新,系统立即调用updateConstraints
        [self.view  layoutIfNeeded];
    }];
updateConstraints
  • 重置/更新约束在这个方法(updateConstraints)
- (void)updateConstraints {
    [self.redView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(130.f);
        make.left.equalTo(self.view.mas_left).offset(20.f);
        make.width.mas_equalTo(180.f);
        make.height.mas_equalTo(90.f);
    }];
    [super updateConstraints];
}
  • 设置requiresConstraintBasedLayout为YES
+ (BOOL)requiresConstraintBasedLayout {
    return YES;
}
注意

使用Masonry不需要设置控件的translatesAutoresizingMaskIntoConstraints属性为NO;
防止block中的循环引用,使用弱引用(这是错误观点),在这里block是局部的引用,block内部引用self不会造成循环引用的
__weak typeof (self) weakSelf = self;(没必要的写法)

有关iOS Masonry布局(一)的更多相关文章

  1. ruby - nanoc 和多种布局 - 2

    是否可以为特定(或所有)项目使用多个布局?例如,我有几个项目,我想对其应用两种不同的布局。一个是绿色的,一个是蓝色的(但是)。我想将它们编译到我的输出目录中的两个不同文件夹中(例如v1和v2)。我一直在玩弄规则和编译block,但我不知道这是怎么回事。因为,每个项目在编译过程中只编译一次,我不能告诉nanoc第一次用layout1编译,第二次用layout2编译。我试过这样的东西,但它导致输出文件损坏。compile'*'doifitem.binary?#don’tfilterbinaryitemselsefilter:erblayout'layout1'layout'layout2'

  2. ruby-on-rails - 我可以在没有 Controller 的情况下直接从 routes.rb 渲染布局吗? - 2

    我想为网站的管理和公共(public)部分设置一对样式指南。每个都需要自己的布局,其中包含静态html和调用erbpartials的混合(因此静态页面不会削减它)。我不需要Controller来为这些页面提供服务,而且我不希望有效的仅开发内容使其余代码困惑。这让我想知道是否有一种方法可以直接呈现布局。免责声明:我明白这不是我应该经常/永远做的事情,而且我知道有很多争论可以解释为什么这是一个坏主意。我对这是否可能感兴趣。有没有办法让我直接从routes.rb渲染布局而不通过Controller? 最佳答案 出于某种奇怪的原因,我想暂时

  3. ruby-on-rails - 设计 Controller 如何改变布局? - 2

    这个问题在这里已经有了答案:differentlayoutforsign_inactionindevise(8个答案)关闭7年前。如何更改设计Controller中的布局?

  4. ruby-on-rails - Rails - 如何在布局中查找域 url - 2

    我有request.env['http_host']在本地主机上工作,但在heroku的布局页面中引用时会导致错误。此请求在View中工作并显示正确的基本url,但是当我将代码移动到布局时它会导致错误。注意-我正在使用它来为html电子邮件中的图像构建绝对url。收到错误:ActionView::Template::Error(undefinedmethod`env'fornil:NilClass): 最佳答案 如果你想要没有端口的主机,只需使用:request.host编辑:糟糕,我刚刚注意到您正在使用View中的代码。我不知道它

  5. Ruby GUI(非复杂布局) - 2

    我对RubyGUI设计做了很多研究,这似乎是Ruby倾向于落后的领域。我探索了MonkeyBars、wxRuby、fxRuby、Shoes等选项,只是想从Ruby社区获得一些意见。虽然它们绝对可用,但每一个的开发似乎都在下降。我在任何(减去fxRuby书)上都找不到大量有用的文档或用户基础。我只是想制作一个简单的GUI,所以我真的不想花费数百小时来学习更复杂的工具的复杂性或尝试使用甚至不再开发的东西(鞋子是应用程序的类型我正在寻找,但它有很多问题并且没有得到积极开发。)在所有选项中,你们会推荐哪个选项是最快的,并且仍然具有某种开发基础?谢谢! 最佳答案

  6. ruby - Rails 渲染 Controller 中的部分和布局 - 2

    我正在覆盖设计注册Controller的创建操作。我有两种注册表格,个人或公司,公司有一个名为company_form的字段设置为true以区分这两种表格。在表单验证后,我希望呈现正确的表单(以前无论我使用什么表单,它都会返回默认表单)。我遇到了一个问题,即只渲染了部分(很明显,因为我只渲染了部分),但我还需要渲染布局/应用程序文件。classRegistrationsControllerifresource.company_formrenderpartial:'shared/company_signup_form'elserenderpartial:'/shared/individu

  7. ruby-on-rails - 缺少带有 { :locale=>[:en], :formats=>[:html], 的模板布局/邮件程序 - 2

    我正在学习michaelharltrails教程,但出现此错误Missingtemplatelayouts/mailerwith{:locale=>[:en],:formats=>[:html],:variants=>[],:handlers=>[:raw,:erb,:html,:builder,:ruby,:coffee,:jbuilder]}.Searchedin:*"/home/ubuntu/workspace/app/views"预览账户激活时这是我的user_mailer.rbclassUserMailer错误突出显示了mailto:user.email,subject:"A

  8. ruby - Sinatra 中的嵌套布局 - 2

    tl;dr:在Sinatra中是否有一种干净的嵌套布局方式?对于我网站上的所有页面,我有一个通用的layout.erb,它呈现页眉、页脚和其他一些位。对于这些页面的一个子集,我想使用内部布局,除了那些公共(public)位之外,它还呈现左侧菜单。全局erb:pageTemplate执行layout.erb,其中yield执行pageTemplate在子集中erb:pageTemplate执行layout.erb,其中yield执行specificLayout.erb,其中yield执行pageTemplate。有道理吗?我对单独的类、before语句和任何其他ruby​​魔法持开放态度

  9. ruby-on-rails - 在 Rails 中是否可以动态加载类布局? - 2

    我需要消息在项目中有不同的布局,是否可以在Rails中做这样的事情?ClassMessages::New谢谢 最佳答案 这对你有帮助classMessagesController 关于ruby-on-rails-在Rails中是否可以动态加载类布局?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/1274999/

  10. ruby - 使用 slim 或 haml 在独立(非 rails)ruby 应用程序中指定布局和模板 - 2

    我正在尝试在独立(非Rails)应用程序中做这样的事情:layout.slim:h1Hello.content=yield显示.slim:=object.name=object.description我不知道如何指定布局和模板。这对slim(或haml)有可能吗?谢谢。 最佳答案 layout.slim文件如下所示:h1Hello.content==yieldcontents.slim文件如下所示:=name这可以缩短,但为了便于解释,我将其分成了各个步骤。require'slim'#Simpleclasstorepresentan

随机推荐