Layoutable是一个为UIView应用程序提供的扩展,使使用Auto Layout变得更容易。此框架不替换UIKit中可用的任何现有Auto Layout API。锚点API非常好且易于使用,但在执行一些常见任务时可能需要大量的代码重复。此框架仅仅增加了一些有用的扩展。您可以在单个文件中查看实现,请参阅以下链接一个单一的文件。
使用方法及特性
以下是如何对屏幕上方的代码进行约束,请参阅以下示例完整版本。
仅使用UIKit
import UIKit
final class ViewController: UIViewController {
private let headerView: UIView = {
let view = UIView()
view.backgroundColor = .white
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
[...]
override func loadView() {
[...]
NSLayoutConstraint.activate([
headerView.topAnchor.constraint(equalTo: view.topAnchor),
headerView.leftAnchor.constraint(equalTo: view.leftAnchor),
headerView.rightAnchor.constraint(equalTo: view.rightAnchor),
headerView.heightAnchor.constraint(equalToConstant: 200),
headerCenterView.widthAnchor.constraint(equalToConstant: 80),
headerCenterView.heightAnchor.constraint(equalToConstant: 80),
headerCenterView.centerXAnchor.constraint(equalTo: headerView.centerXAnchor),
headerCenterView.centerYAnchor.constraint(equalTo: headerView.centerYAnchor),
contentContainerView.topAnchor.constraint(equalTo: headerView.bottomAnchor),
contentContainerView.leftAnchor.constraint(equalTo: view.leftAnchor),
contentContainerView.rightAnchor.constraint(equalTo: view.rightAnchor),
contentContainerView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
contentView.topAnchor.constraint(equalTo: contentContainerView.topAnchor, constant: 80),
contentView.leftAnchor.constraint(equalTo: contentContainerView.leftAnchor, constant: 20),
contentView.rightAnchor.constraint(equalTo: contentContainerView.rightAnchor, constant: -20),
contentView.bottomAnchor.constraint(equalTo: contentContainerView.bottomAnchor, constant: -20),
])
}
}
UIKit + Layoutable
import UIKit
import Layoutable
final class ViewController: UIViewController {
private let headerView: UIView = {
let view = UIView()
view.backgroundColor = .white
return view.layoutable()
}()
[...]
override func loadView() {
[...]
headerView.constrainToSuperviewEdges(excluding: [.bottom])
headerView.heightAnchor.constraint(equalToConstant: 200).isActive = true
headerCenterView.constrainToConstant(size: .init(width: 80, height: 80))
headerCenterView.constrainCenterToSuperview()
contentContainerView.constrainToSuperviewEdges(excluding: [.top])
contentContainerView.topAnchor.constraint(equalTo: headerView.bottomAnchor).isActive = true
contentView.constrainToSuperviewEdges(insets: .init(top: 80, left: 20, bottom: 20, right: 20))
}
}
检测视图是否可用于Auto Layout
对于那些您想要与Auto Layout一起使用的视图,您需要键入translatesAutoresizingMaskIntoConstraints = false
。很容易忘记,在运行您的应用程序后会导致很多冲突。Layoutable检查这种状况,并告知您如何修复它。
需求
Layoutable 支持iOS 9.0或更高版本。
安装
Carthage
如果你使用Carthage,请将以下依赖项添加到你的Cartfile
github "MichalTKwiecien/Layoutable" {version}
CocoaPods
如果你使用CocoaPods,请将以下依赖项添加到你的Podfile
pod 'Layoutable', '~> {version}'
手动
您只需将单文件拖放到项目中。
贡献
开发需要以下工具
在克隆仓库后,安装项目依赖项
$ carthage bootstrap --platform iOS