AutoLayoutHelperSwift 1.0.2

AutoLayoutHelperSwift 1.0.2

测试已测试
语言语言 SwiftSwift
许可协议 MIT
发布最新发布2016 年 11 月
SwiftSwift 版本3.0
SPM支持 SPM

Daniela DiasShagun Madhikarmi 维护。



  • Shagun Madhikarmi 和 Daniela Dias 编写

AutoLayoutHelper

UIView 扩展,用于轻松创建常用的 iOS 自动布局约束。

问题

在 iOS 9 的自动布局 API 之前,使用自动布局的编程方式可以是相当冗长的,即构建每个规则对应的 NSLayoutConstraint 对象,或者是容易出错的,例如(使用 视觉格式语言字符串

解决方案

我们可以将创建常见 NSLayoutConstraint 关系的操作转换为一些可重用的方法,我们可以在任何继承自 UIView 的类上调用这些方法。我们还确保创建的约束会被添加到视图的父视图。

这意味着您可以使用所需的 NSLayoutAttributeNSLayoutRelation 将一个视图与另一个视图相关联,作为视图设置的一部分,这还有助于我们保持代码的 DRY

依赖项

要求

  • iOS 7+
  • tvOS 9+

安装

手动

  • UIView+AutoLayoutHelper.swift 文件添加到您的 Xcode 项目中。
  • 注意。即将推出动态框架目标!

用法

示例

填充父视图

UIView 添加 NSLayoutConstraint 关系,使其顶部、左侧、右侧和底部边缘与其父视图相关联

// Create view

let leftView = UIView()
leftView.backgroundColor = UIColor.red
view.addSubview(leftView)

// Add constraints

leftView.addTopConstraint(toView: superview, attribute: .top, relation: .equal, constant: 10.0)
leftView.addLeadingConstraint(toView: superview, attribute: .leading, relation: .equal, constant: 10.0)
leftView.addTrailingConstraint(toView: superview, attribute: .trailing, relation: .equal, constant: -10.0)
leftView.addBottomConstraint(toView: superview, attribute: .bottom, relation: .equal, constant: -10.0)

或者,更简洁地省略属性

leftView.addTopConstraint(toView: superview, constant: 10.0)
leftView.addLeadingConstraint(toView: superview, constant: 10.0)
leftView.addTrailingConstraint(toView: superview, constant: -10.0)
leftView.addBottomConstraint(toView: superview, constant: -10.0)

或者甚至更简洁地使用 fillSuperView(通过 @danieladias

let edgeInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0)
leftView.fillSuperView(edgeInsets)

居中

向一个 UIView 添加约束,使其在父视图中垂直(Y 轴)和水平(X 轴)居中

label.addCenterXConstraintToView(label.superview, relation: .equal, constant:0.0)
label.addCenterYConstraintToView(label.superview, relation: .equal, constant:0.0)

添加固定宽度和高度的约束

view.addWidthConstraintWithRelation: .equal, constant:100.0)
view.addHeightConstraintWithRelation: .equal, constant:80.0)

修改约束(因为方法返回这些约束给你)

// Create a reference to the `NSLayoutConstraint` e.g. for height

heightConstraint = view.addHeightConstraint(toView: nil, constant: 80.0)

...

// Update the height constant

heightConstraint.constant = 30.0;

// Animate changes

UIView.animateWithDuration(0.3, animations: { () -> Void in

    view.layoutIfNeeded()
})

贡献

请注意,该项目是以贡献者行为准则发布的。通过参与此项目,您同意遵守其条款。请参阅 行为准则 文件

维护者

联系方式

[email protected]

许可证

AutoLayoutHelper 在 MIT 许可下发布。请参阅 许可证