snapkit equalto和multipliedby方法
最近在使用snapkit过程中遇到一个问题,在github上搜索之后发现另外一个有趣的问题
frameImageContainer.snp.makeConstraints({ (make) in
make.width.equalTo().multipliedBy(0.2)
make.height.equalTo().multipliedBy(0.2)
make.top.equalToSuperview().offset(self.view.frame.height/)
make.centerX.equalToSuperview();
})
看起来很理所当然的,明显不可以这样写,但是具体是什么原因呢,明明没有报任何错误和警告,但是.multipliedBy()方法却没有效果,那我们来看一下snapkit源码。
1.首先点进equalTo()方法,代码是这样的:
@discardableResult
public func equalTo(_ other: ConstraintRelatableTarget, _ file: String = #file, _ line: UInt = #line) -> ConstraintMakerEditable {
return self.relatedTo(other, relation: .equal, file: file, line: line)
}
再点进relatedTo()方法:
internal func relatedTo(_ other: ConstraintRelatableTarget, relation: ConstraintRelation, file: String, line: UInt) -> ConstraintMakerEditable {
let related: ConstraintItem
let constant: ConstraintConstantTarget
if let other = other as? ConstraintItem {
guard other.attributes == ConstraintAttributes.none ||
other.attributes.layoutAttributes.count <= ||
other.attributes.layoutAttributes == self.description.attributes.layoutAttributes ||
other.attributes == .edges && self.description.attributes == .margins ||
other.attributes == .margins && self.description.attributes == .edges else {
fatalError("Cannot constraint to multiple non identical attributes. (\(file), \(line))");
}
related = other
constant = 0.0
} else if let other = other as? ConstraintView {
related = ConstraintItem(target: other, attributes: ConstraintAttributes.none)
constant = 0.0
} else if let other = other as? ConstraintConstantTarget {
related = ConstraintItem(target: nil, attributes: ConstraintAttributes.none)
constant = other
} else if #available(iOS 9.0, OSX 10.11, *), let other = other as? ConstraintLayoutGuide {
related = ConstraintItem(target: other, attributes: ConstraintAttributes.none)
constant = 0.0
} else {
fatalError("Invalid constraint. (\(file), \(line))")
}
let editable = ConstraintMakerEditable(self.description)
editable.description.sourceLocation = (file, line)
editable.description.relation = relation
editable.description.related = related
editable.description.constant = constant
return editable
}
可以看到上面红色部分,此时other可以转换为ConstraintConstantTarget类型,设置related的target为nil,attributes为none,constant设置为other,最后将这些变量赋值给description属性保存。
2.multipliedBy()方法:
@discardableResult
public func multipliedBy(_ amount: ConstraintMultiplierTarget) -> ConstraintMakerEditable {
self.description.multiplier = amount
return self
}
可以看到,multipliedBy方法中只是简单的赋值,将amout值复制到description中保存。
3.再来看一下makeConstraints()方法:
internal static func makeConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) {
let maker = ConstraintMaker(item: item)
closure(maker)
var constraints: [Constraint] = []
for description in maker.descriptions {
guard let constraint = description.constraint else {
continue
}
constraints.append(constraint)
}
for constraint in constraints {
constraint.activateIfNeeded(updatingExisting: false)
}
}
首先将要添加约束的对象封装成ConstraintMaker对象,再把它作为参数调用closure,开始添加约束。closure中的每条语句会先被解析ConstraintDescription对象,添加到maker的descriptions属性中。 在第一个for循环中可以看到,每次循环从descriptions中取出一条description,判断是否改description是否有constraint属性;
constraint属性使用的懒加载,值为:
internal lazy var constraint: Constraint? = {
guard let relation = self.relation,
let related = self.related,
let sourceLocation = self.sourceLocation else {
return nil
}
let from = ConstraintItem(target: self.item, attributes: self.attributes)
return Constraint(
from: from,
to: related,
relation: relation,
sourceLocation: sourceLocation,
label: self.label,
multiplier: self.multiplier,
constant: self.constant,
priority: self.priority
)
}()
先判断relation,related,sourceLocation的值是否为nil,若为nil则返回nil,否则就根据description属性创建一个Constraint对象并返回。
Constraint的构造方法:
internal init(from: ConstraintItem,
to: ConstraintItem,
relation: ConstraintRelation,
sourceLocation: (String, UInt),
label: String?,
multiplier: ConstraintMultiplierTarget,
constant: ConstraintConstantTarget,
priority: ConstraintPriorityTarget) {
self.from = from
self.to = to
self.relation = relation
self.sourceLocation = sourceLocation
self.label = label
self.multiplier = multiplier
self.constant = constant
self.priority = priority
self.layoutConstraints = [] // get attributes
let layoutFromAttributes = self.from.attributes.layoutAttributes
let layoutToAttributes = self.to.attributes.layoutAttributes // get layout from
let layoutFrom = self.from.layoutConstraintItem! // get relation
let layoutRelation = self.relation.layoutRelation for layoutFromAttribute in layoutFromAttributes {
// get layout to attribute
let layoutToAttribute: LayoutAttribute
#if os(iOS) || os(tvOS)
if layoutToAttributes.count > {
if self.from.attributes == .edges && self.to.attributes == .margins {
switch layoutFromAttribute {
case .left:
layoutToAttribute = .leftMargin
case .right:
layoutToAttribute = .rightMargin
case .top:
layoutToAttribute = .topMargin
case .bottom:
layoutToAttribute = .bottomMargin
default:
fatalError()
}
} else if self.from.attributes == .margins && self.to.attributes == .edges {
switch layoutFromAttribute {
case .leftMargin:
layoutToAttribute = .left
case .rightMargin:
layoutToAttribute = .right
case .topMargin:
layoutToAttribute = .top
case .bottomMargin:
layoutToAttribute = .bottom
default:
fatalError()
}
} else if self.from.attributes == self.to.attributes {
layoutToAttribute = layoutFromAttribute
} else {
layoutToAttribute = layoutToAttributes[]
}
} else {
if self.to.target == nil && (layoutFromAttribute == .centerX || layoutFromAttribute == .centerY) {
layoutToAttribute = layoutFromAttribute == .centerX ? .left : .top
} else {
layoutToAttribute = layoutFromAttribute
}
}
#else
if self.from.attributes == self.to.attributes {
layoutToAttribute = layoutFromAttribute
} else if layoutToAttributes.count > {
layoutToAttribute = layoutToAttributes[]
} else {
layoutToAttribute = layoutFromAttribute
}
#endif // get layout constant
let layoutConstant: CGFloat = self.constant.constraintConstantTargetValueFor(layoutAttribute: layoutToAttribute) // get layout to
var layoutTo: AnyObject? = self.to.target // use superview if possible
if layoutTo == nil && layoutToAttribute != .width && layoutToAttribute != .height {
layoutTo = layoutFrom.superview
} // create layout constraint
let layoutConstraint = LayoutConstraint(
item: layoutFrom,
attribute: layoutFromAttribute,
relatedBy: layoutRelation,
toItem: layoutTo,
attribute: layoutToAttribute,
multiplier: self.multiplier.constraintMultiplierTargetValue,
constant: layoutConstant
) // set label
layoutConstraint.label = self.label // set priority
layoutConstraint.priority = LayoutPriority(rawValue: self.priority.constraintPriorityTargetValue) // set constraint
layoutConstraint.constraint = self // append
self.layoutConstraints.append(layoutConstraint)
}
}
重点看红色部分,遍历layoutAttributes,并根据layoutAttribute的值生成一个LayoutConstraint对象添加到layoutConstraints数组中。LayoutConstraint继承自系统类NSLayoutConstraint。
4.最后再看3中的第二个for循环,使用activeIfNeeded()方法激活约束:
internal func activateIfNeeded(updatingExisting: Bool = false) {
guard let item = self.from.layoutConstraintItem else {
print("WARNING: SnapKit failed to get from item from constraint. Activate will be a no-op.")
return
}
let layoutConstraints = self.layoutConstraints
if updatingExisting {
var existingLayoutConstraints: [LayoutConstraint] = []
for constraint in item.constraints {
existingLayoutConstraints += constraint.layoutConstraints
}
for layoutConstraint in layoutConstraints {
let existingLayoutConstraint = existingLayoutConstraints.first { $ == layoutConstraint }
guard let updateLayoutConstraint = existingLayoutConstraint else {
fatalError("Updated constraint could not find existing matching constraint to update: \(layoutConstraint)")
}
let updateLayoutAttribute = (updateLayoutConstraint.secondAttribute == .notAnAttribute) ? updateLayoutConstraint.firstAttribute : updateLayoutConstraint.secondAttribute
updateLayoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: updateLayoutAttribute)
}
} else {
NSLayoutConstraint.activate(layoutConstraints)
item.add(constraints: [self])
}
}
当updatingExisting为false时,进入else语句,使用的系统类NSLayoutConstraint的方法激活约束:
/* Convenience method that activates each constraint in the contained array, in the same manner as setting active=YES. This is often more efficient than activating each constraint individually. */
@available(iOS 8.0, *)
open class func activate(_ constraints: [NSLayoutConstraint])
并将设置过的约束添加到item的constraintSet这个私有属性中:
internal var constraints: [Constraint] {
return self.constraintsSet.allObjects as! [Constraint]
}
internal func add(constraints: [Constraint]) {
let constraintsSet = self.constraintsSet
for constraint in constraints {
constraintsSet.add(constraint)
}
}
internal func remove(constraints: [Constraint]) {
let constraintsSet = self.constraintsSet
for constraint in constraints {
constraintsSet.remove(constraint)
}
}
private var constraintsSet: NSMutableSet {
let constraintsSet: NSMutableSet
if let existing = objc_getAssociatedObject(self, &constraintsKey) as? NSMutableSet {
constraintsSet = existing
} else {
constraintsSet = NSMutableSet()
objc_setAssociatedObject(self, &constraintsKey, constraintsSet, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
return constraintsSet
}
5.通过这个过程不难发现,使用make.width.equalTo(295).multipliedBy(0.2) 这种方式不能得到想要的结果。在3中Constraint的构造方法的红色部分,其实构造LayoutConstraint对象时调用的NSLayoutConstraint的便利构造器方法:
/* Create constraints explicitly. Constraints are of the form "view1.attr1 = view2.attr2 * multiplier + constant"
If your equation does not have a second view and attribute, use nil and NSLayoutAttributeNotAnAttribute.
*/
public convenience init(item view1: Any, attribute attr1: NSLayoutConstraint.Attribute, relatedBy relation: NSLayoutConstraint.Relation, toItem view2: Any?, attribute attr2: NSLayoutConstraint.Attribute, multiplier: CGFloat, constant c: CGFloat)
注意上面注释 view1.attr1 = view2.attr2 * multiplier + constant 如果只设置为数字,则相当于view2为nil,所以view1的属性值只能等于constant的值,不会乘以multiplier。
6.终于写完了,哈哈。 demo工程地址,对应的方法已打断点,可以跟着代码一步步调试,有助于理解。
疑问:在4中最后一部分红色字体的内容,私有属性constraintsSet为啥不直接使用,还要使用runtime给当前对象绑定一个同名的属性,每次使用时获取绑定的属性的值,不懂,希望知道的同学不吝赐教。
snapkit equalto和multipliedby方法的更多相关文章
- Swift - 自动布局库SnapKit的使用详解1(配置、使用方法、样例)
为了适应各种屏幕尺寸,iOS 6后引入了自动布局(Auto Layout)的概念,通过使用各种 Constraint(约束)来实现页面自适应弹性布局. 在 StoryBoard 中使用约束实现自动布局 ...
- swift约束框架SnapKit使用
一.Swift - 自动布局库SnapKit的使用详解1(配置.使用方法.样例) 为了适应各种屏幕尺寸,iOS 6后引入了自动布局(Auto Layout)的概念,通过使用各种 Constrain ...
- iOS SnapKit自动布局使用详解
对于自动布局: 我们在 StoryBoard 中可以使用约束实现,简单明了,但如果用纯代码来设置约束就很麻烦了 OC里面,我们常用的有Masonry,SDAutoLayout Swift里,我们有Sn ...
- iOS SnapKit自动布局使用详解(Swift版Masonry)
对于自动布局: 我们在 StoryBoard 中可以使用约束实现,简单明了,但如果用纯代码来设置约束就很麻烦了 OC里面,我们常用的有Masonry,SDAutoLayout Swift里,我们有Sn ...
- snapkit更新约束崩溃的问题
最近在使用snapkit布局时,竟然发现更新约束会导致崩溃,为什么这样呢? checkButton.snp.makeConstraints { (make) in make.left.top.equa ...
- AutoLayout框架Masonry使用心得
AutoLayout框架Masonry使用心得 字数1769 阅读1481 评论1 喜欢17 我们组分享会上分享了页面布局的一些写法,中途提到了AutoLayout,会后我决定将很久前挖的一个坑给填起 ...
- IOS自适应库---- Masonry的使用
Masonry是一个轻量级的布局框架,拥有自己的描述语法,采用更优雅的链式语法封装自动布局,简洁明了并具有高可读性,而且同时支持 iOS 和 Max OS X.Masonry是一个用代码写iOS或OS ...
- iOS-屏幕适配-UI布局
iOS 屏幕适配:autoResizing autoLayout和sizeClass 一.图片解说 -------------------------------------------------- ...
- Coding源码学习第四部分(Masonry介绍与使用(二))
接上篇,本篇继续对Masonry 进行学习,接上篇示例: (6)Masonry 布局实现iOS 计算器 - (void)exp4 { WS(weakSelf); // 申明区域,displayView ...
随机推荐
- React—Native开发之原生模块向JavaScript发送事件
首先,由RN中文网关于原生模块(Android)的介绍可以看到,RN前端与原生模块之 间通信,主要有三种方法: (1)使用回调函数Callback,它提供了一个函数来把返回值传回给JavaScript ...
- JAVA视频网盘分享
JAVA视频网盘分享 [涵盖从java入门到深入架构,Linux.云计算.分布式.大数据Hadoop.ios.Android.互联网技术应有尽有] 1.JavaScript视频教程 链接: http: ...
- OneNet平台初探成功
1.经过半个月的研究,终于成功对接OneNet平台,实现远程控制LED灯的亮灭 2.在调试的过程中也遇到了很多问题,做一下总结 3.硬件:STM32F103C8T6的最小系统板,ESP8266-WiF ...
- Python3 循环语句
Python3 循环语句 转来的 很适合小白 感谢作者 Python中的循环语句有 for 和 while. Python循环语句的控制结构图如下所示: while 循环 Python中wh ...
- JS BOM对象 History对象 Location对象
一.BOM对象 BOM(浏览器对象模型),可以对浏览器窗口进行访问和操作 window对象 所有浏览器都支持 window 对象. 概念上讲.一个html文档对应一个window对象. 功能上讲: 控 ...
- gitlab的仓库迁移到新的gitlab
1.下载原有gitlab源码 git clone http://gitlab.**.com/projectName gitlab地址替换成为新gitlab地址 git remote set-url o ...
- 第六章 函数、谓词、CASE表达式 6-3 CASE表达式
一.什么是CASE表达式 CASE表达式是一种运算功能,意味着CASE表达式也是函数的一种. 它是SQL中数一数二的重要功能.必须好好学习掌握. CASE表达式是在区分情况时使用的,这种情况的区分 ...
- EF实体对象解耦 - 泛型联表查询
为了达到模块间最小耦合,单模块业务数据不与其他模块发生关系.在操作数据库的时候,采用EF泛型操作.但泛型操作不好实现联表,经过一晚的试验发现了一种定义数据库上下文并联表的方式. 1.实体对象定义.实体 ...
- 定制NSError
定制NSError 效果: 系统的NSError是可以自己定制的,以下提供代码来实现并表示如何使用: YXError.h 与 YXError.m // // YXError.h // CustomYX ...
- [翻译] INSSearchBar
INSSearchBar 效果: An animating search bar. 一个带动画效果的search bar. Originally developed for ShopNow v2. ( ...