AutoLayout

AutoLayout

通过参照和约束完成目标布局

Constraints(约束)

一个AutoLayout约束是NSLayoutConstraint的一个实例

init(item: Any, attribute: NSLayoutAttribute, relatedBy: NSLayoutRelation, toItem: Any?, attribute: NSLayoutAttribute, multiplier: CGFloat, constant: CGFloat)
Creates a constraint that defines the relationship between the specified attributes of the given views.

Item == item1 需要设置约束的控件
attribute == attribute1 需要设置的约束
relatedBy == relation item1 与 item2 之间的关系
toItem == item2 被参照的控件
attribute == attribute2 需要设置的约束
multiplier == multiplier 乘以
constant = constant 加上
item1.attribute1 = multiplier × item2.attribute2 + constant
如果约束是描述自身的属性,那么 item2 设为 nil ,attribute2 设置为 notAnAttribute 。

public enum NSLayoutRelation : Int {

    case lessThanOrEqual
    case equal
    case greaterThanOrEqual
}
public enum NSLayoutAttribute : Int {
   
    case left  
    case right
    case top
    case bottom
    case leading  //Left/Right 和 Leading/Trailing的区别是Left/Right永远是指左右,而Leading/Trailing在某些从右至左习惯的地区会变成,leading是右边,trailing是左边。
    case trailing  
    case width
    case height
    case centerX
    case centerY
    case lastBaseline  // 文字的下基线
   
    @available(iOS 8.0, *)
    case firstBaseline  //上基线
    //Margin 多出一些边界属性
    @available(iOS 8.0, *)
    case leftMargin
    @available(iOS 8.0, *)
    case rightMargin
    @available(iOS 8.0, *)
    case topMargin
    @available(iOS 8.0, *)
    case bottomMargin
    @available(iOS 8.0, *)
    case leadingMargin
    @available(iOS 8.0, *)
    case trailingMargin
    @available(iOS 8.0, *)
    case centerXWithinMargins
    @available(iOS 8.0, *)
    case centerYWithinMargins

    case notAnAttribute
}

NSLayoutAnchor(描述约束关系)

extension UIView {

    /* Constraint creation conveniences. See NSLayoutAnchor.h for details.
     */
    @available(iOS 9.0, *)
    open var leadingAnchor: NSLayoutXAxisAnchor { get }

    @available(iOS 9.0, *)
    open var trailingAnchor: NSLayoutXAxisAnchor { get }

    @available(iOS 9.0, *)
    open var leftAnchor: NSLayoutXAxisAnchor { get }

    @available(iOS 9.0, *)
    open var rightAnchor: NSLayoutXAxisAnchor { get }

    @available(iOS 9.0, *)
    open var topAnchor: NSLayoutYAxisAnchor { get }

    @available(iOS 9.0, *)
    open var bottomAnchor: NSLayoutYAxisAnchor { get }

    @available(iOS 9.0, *)
    open var widthAnchor: NSLayoutDimension { get }

    @available(iOS 9.0, *)
    open var heightAnchor: NSLayoutDimension { get }

    @available(iOS 9.0, *)
    open var centerXAnchor: NSLayoutXAxisAnchor { get }

    @available(iOS 9.0, *)
    open var centerYAnchor: NSLayoutYAxisAnchor { get }

    @available(iOS 9.0, *)
    open var firstBaselineAnchor: NSLayoutYAxisAnchor { get }

    @available(iOS 9.0, *)
    open var lastBaselineAnchor: NSLayoutYAxisAnchor { get }
}

左右边距SLayoutXAxisAnchor , 上下边距NSLayoutYAxisAnchor , 宽高NSLayoutDimension

// Creating constraints using NSLayoutConstraint
NSLayoutConstraint(item: subview,
                   attribute: .Leading,
                   relatedBy: .Equal,
                   toItem: view,
                   attribute: .LeadingMargin,
                   multiplier: 1.0,
                   constant: 0.0).active = true
 
NSLayoutConstraint(item: subview,
                   attribute: .Trailing,
                   relatedBy: .Equal,
                   toItem: view,
                   attribute: .TrailingMargin,
                   multiplier: 1.0,
                   constant: 0.0).active = true
 
 
// Creating the same constraints using Layout Anchors
let margins = view.layoutMarginsGuide
 
subview.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor).active = true
subview.trailingAnchor.constraintEqualToAnchor(margins.trailingAnchor).active = true

Visual format (可视化格式语言)

open class func constraints(withVisualFormat format: String, options opts: NSLayoutFormatOptions = [], metrics: [String : Any]?, views: [String : Any]) -> [NSLayoutConstraint]
format: VFL语句
opts: 对齐方式
metrics:VFL语句 参数是一个放numeric值的字典,允许你用name解释一个numeric数值
views:VFL语句中用到的控件
metrics:可以把VFL语句中的常量,抽取成为变量。由于是个字典,要包装成对象类型

[view(30)]配合方向 水平方向就是为宽度 垂直则为高度
-(>=100)-[view]距父视图的左边距离大于等于100
[v1(>=20@400,<=30)]``@是优先级
H: V: H 说明之后的句子都是在水平方向设置约束的 V 则是垂直方向。默认方向为 H 水平方向

private func setContainerView() {
        
        let containerView = UIView()
        addSubview(containerView)
        
        containerView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraints(format: "H:|-90-[v0]|", views: containerView)
        addConstraints(format: "V:[v0(60)]", views: containerView)
        addConstraint(NSLayoutConstraint(item: containerView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        
        containerView.addSubview(nameLabel)
        containerView.addSubview(messageLabel)
        containerView.addSubview(timeLabel)
        containerView.addSubview(hasReadImageView)
        
        hasReadImageView.image = UIImage(named: "33")
        
        addConstraints(format: "H:|[v0][v1(80)]-12-|", views: nameLabel, timeLabel)
        addConstraints(format: "V:|[v0][v1(30)]|", views: nameLabel, messageLabel)
        addConstraints(format: "H:|[v0]-8-[v1(20)]-12-|", views: messageLabel, hasReadImageView)
        addConstraints(format: "V:|[v0(30)]", views: timeLabel)
        addConstraints(format: "V:[v0(30)]|", views: hasReadImageView)
    }

extension UIView{
    
    func addConstraints(format: String, views: UIView...) {
        var viewsDictionary = [String: UIView]()
        for (index, view) in views.enumerated(){
            let key = "v\(index)"
            viewsDictionary[key] = view
            view.translatesAutoresizingMaskIntoConstraints = false
        }
        
        addConstraints(NSLayoutConstraint.constraints(withVisualFormat: format, options: NSLayoutFormatOptions(), metrics: nil, views: viewsDictionary))
        
    }
}
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 适配 什么是适配? 适应、兼容各种不同的情况 移动开发中,适配的常见种类 系统适配 针对不同版本的操作系统进行适配...
    JonesCxy阅读 908评论 1 6
  • 主要功能是使用约束,对视图进行相对布局,以适应不同屏尺的变换。 网上大量的资料都在介绍xib和storyboard...
    奉行尹先生阅读 1,044评论 0 2
  • AutoLayout不是一个必须要使用的技术,你可以选择使用它或者不适用它。 一个View可以通过以下三种方式来使...
    smalldu阅读 1,523评论 0 4
  • 一. 为什么要使用自动布局 FrameiPhone4S 320*480 iPhone5 5S 320*568...
    Vinc阅读 500评论 0 9
  • 一、简介 在以前的iOS程序中,经常编写大量的坐标计算代码,为了保证在3.5 inch和4.0 inch屏幕上都能...
    温暖C阅读 1,689评论 0 2