Constraint.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. //
  2. // Constraint.swift
  3. // Snappy
  4. //
  5. // Copyright (c) 2011-2014 Masonry Team - https://github.com/Masonry
  6. //
  7. // Permission is hereby granted, free of charge, to any person obtaining a copy
  8. // of this software and associated documentation files (the "Software"), to deal
  9. // in the Software without restriction, including without limitation the rights
  10. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. // copies of the Software, and to permit persons to whom the Software is
  12. // furnished to do so, subject to the following conditions:
  13. //
  14. // The above copyright notice and this permission notice shall be included in
  15. // all copies or substantial portions of the Software.
  16. //
  17. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. // THE SOFTWARE.
  24. import UIKit
  25. /**
  26. * ConstraintAttributes is an options set that maps to NSLayoutAttributes.
  27. */
  28. struct ConstraintAttributes: RawOptionSet {
  29. var value: UInt
  30. init(_ value: UInt) {
  31. self.value = value
  32. }
  33. func toRaw() -> UInt { return self.value }
  34. func getLogicValue() -> Bool { return self.value != 0 }
  35. static func fromRaw(raw: UInt) -> ConstraintAttributes? { return self(raw) }
  36. static func fromMask(raw: UInt) -> ConstraintAttributes { return self(raw) }
  37. static func convertFromNilLiteral() -> ConstraintAttributes { return self(0) }
  38. static var None: ConstraintAttributes { return self(0) }
  39. static var Left: ConstraintAttributes { return self(1) }
  40. static var Top: ConstraintAttributes { return self(2) }
  41. static var Right: ConstraintAttributes { return self(4) }
  42. static var Bottom: ConstraintAttributes { return self(8) }
  43. static var Leading: ConstraintAttributes { return self(16) }
  44. static var Trailing: ConstraintAttributes { return self(32) }
  45. static var Width: ConstraintAttributes { return self(64) }
  46. static var Height: ConstraintAttributes { return self(128) }
  47. static var CenterX: ConstraintAttributes { return self(256) }
  48. static var CenterY: ConstraintAttributes { return self(512) }
  49. static var Baseline: ConstraintAttributes { return self(1024) }
  50. static var Edges: ConstraintAttributes { return self(15) }
  51. static var Size: ConstraintAttributes { return self(192) }
  52. static var Center: ConstraintAttributes { return self(768) }
  53. var layoutAttributes:Array<NSLayoutAttribute> {
  54. var attrs: Array<NSLayoutAttribute> = []
  55. if (self & ConstraintAttributes.Left) {
  56. attrs.append(.Left)
  57. }
  58. if (self & ConstraintAttributes.Top) {
  59. attrs.append(.Top)
  60. }
  61. if (self & ConstraintAttributes.Right) {
  62. attrs.append(.Right)
  63. }
  64. if (self & ConstraintAttributes.Bottom) {
  65. attrs.append(.Bottom)
  66. }
  67. if (self & ConstraintAttributes.Leading) {
  68. attrs.append(.Leading)
  69. }
  70. if (self & ConstraintAttributes.Trailing) {
  71. attrs.append(.Trailing)
  72. }
  73. if (self & ConstraintAttributes.Width) {
  74. attrs.append(.Width)
  75. }
  76. if (self & ConstraintAttributes.Height ){
  77. attrs.append(.Height)
  78. }
  79. if (self & ConstraintAttributes.CenterX) {
  80. attrs.append(.CenterX)
  81. }
  82. if (self & ConstraintAttributes.CenterY) {
  83. attrs.append(.CenterY)
  84. }
  85. if (self & ConstraintAttributes.Baseline) {
  86. attrs.append(.Baseline)
  87. }
  88. return attrs
  89. }
  90. }
  91. @assignment func += (inout left: ConstraintAttributes, right: ConstraintAttributes) {
  92. left = (left | right)
  93. }
  94. @assignment func -= (inout left: ConstraintAttributes, right: ConstraintAttributes) {
  95. left = ConstraintAttributes(left.toRaw() & ~right.toRaw())
  96. }
  97. /**
  98. * ConstraintRelation is an Int enum that maps to NSLayoutRelation.
  99. */
  100. enum ConstraintRelation: Int {
  101. case Equal = 1, LessThanOrEqualTo, GreaterThanOrEqualTo
  102. var layoutRelation: NSLayoutRelation {
  103. get {
  104. switch(self) {
  105. case .LessThanOrEqualTo:
  106. return .LessThanOrEqual
  107. case .GreaterThanOrEqualTo:
  108. return .GreaterThanOrEqual
  109. default:
  110. return .Equal
  111. }
  112. }
  113. }
  114. }
  115. /**
  116. * ConstraintItem is a class that is used while building constraints.
  117. */
  118. class ConstraintItem {
  119. init(view: View?, attributes: ConstraintAttributes) {
  120. self.view = view
  121. self.attributes = attributes
  122. }
  123. internal weak var view: View?
  124. internal var attributes: ConstraintAttributes
  125. }
  126. /**
  127. * Constraint is a single item that defines all the properties for a single ConstraintMaker chain
  128. */
  129. class Constraint {
  130. var left: Constraint { return addConstraint(ConstraintAttributes.Left) }
  131. var top: Constraint { return addConstraint(ConstraintAttributes.Top) }
  132. var right: Constraint { return addConstraint(ConstraintAttributes.Right) }
  133. var bottom: Constraint { return addConstraint(ConstraintAttributes.Bottom) }
  134. var leading: Constraint { return addConstraint(ConstraintAttributes.Leading) }
  135. var trailing: Constraint { return addConstraint(ConstraintAttributes.Trailing) }
  136. var width: Constraint { return addConstraint(ConstraintAttributes.Width) }
  137. var height: Constraint { return addConstraint(ConstraintAttributes.Height) }
  138. var centerX: Constraint { return addConstraint(ConstraintAttributes.CenterX) }
  139. var centerY: Constraint { return addConstraint(ConstraintAttributes.CenterY) }
  140. var baseline: Constraint { return addConstraint(ConstraintAttributes.Baseline) }
  141. var and: Constraint { return self }
  142. var with: Constraint { return self }
  143. // MARK: initializer
  144. init(fromItem: ConstraintItem) {
  145. self.fromItem = fromItem
  146. self.toItem = ConstraintItem(view: nil, attributes: ConstraintAttributes.None)
  147. }
  148. // MARK: equalTo
  149. func equalTo(other: ConstraintItem) -> Constraint {
  150. return constrainTo(other, relation: .Equal)
  151. }
  152. func equalTo(other: View) -> Constraint {
  153. return constrainTo(other, relation: .Equal)
  154. }
  155. func equalTo(other: Float) -> Constraint {
  156. return constrainTo(other, relation: .Equal)
  157. }
  158. func equalTo(other: Int) -> Constraint {
  159. return constrainTo(Float(other), relation: .Equal)
  160. }
  161. func equalTo(other: CGSize) -> Constraint {
  162. return constrainTo(other, relation: .Equal)
  163. }
  164. func equalTo(other: CGPoint) -> Constraint {
  165. return constrainTo(other, relation: .Equal)
  166. }
  167. func equalTo(other: UIEdgeInsets) -> Constraint {
  168. return constrainTo(other, relation: .Equal)
  169. }
  170. // MARK: lessThanOrEqualTo
  171. func lessThanOrEqualTo(other: ConstraintItem) -> Constraint {
  172. return constrainTo(other, relation: .LessThanOrEqualTo)
  173. }
  174. func lessThanOrEqualTo(other: View) -> Constraint {
  175. return constrainTo(other, relation: .LessThanOrEqualTo)
  176. }
  177. func lessThanOrEqualTo(other: Float) -> Constraint {
  178. return constrainTo(other, relation: .LessThanOrEqualTo)
  179. }
  180. func lessThanOrEqualTo(other: Int) -> Constraint {
  181. return constrainTo(Float(other), relation: .LessThanOrEqualTo)
  182. }
  183. func lessThanOrEqualTo(other: CGSize) -> Constraint {
  184. return constrainTo(other, relation: .LessThanOrEqualTo)
  185. }
  186. func lessThanOrEqualTo(other: CGPoint) -> Constraint {
  187. return constrainTo(other, relation: .LessThanOrEqualTo)
  188. }
  189. func lessThanOrEqualTo(other: UIEdgeInsets) -> Constraint {
  190. return constrainTo(other, relation: .LessThanOrEqualTo)
  191. }
  192. // MARK: greaterThanOrEqualTo
  193. func greaterThanOrEqualTo(other: ConstraintItem) -> Constraint {
  194. return constrainTo(other, relation: .GreaterThanOrEqualTo)
  195. }
  196. func greaterThanOrEqualTo(other: View) -> Constraint {
  197. return constrainTo(other, relation: .GreaterThanOrEqualTo)
  198. }
  199. func greaterThanOrEqualTo(other: Float) -> Constraint {
  200. return constrainTo(other, relation: .GreaterThanOrEqualTo)
  201. }
  202. func greaterThanOrEqualTo(other: Int) -> Constraint {
  203. return constrainTo(Float(other), relation: .GreaterThanOrEqualTo)
  204. }
  205. func greaterThanOrEqualTo(other: CGSize) -> Constraint {
  206. return constrainTo(other, relation: .GreaterThanOrEqualTo)
  207. }
  208. func greaterThanOrEqualTo(other: CGPoint) -> Constraint {
  209. return constrainTo(other, relation: .GreaterThanOrEqualTo)
  210. }
  211. func greaterThanOrEqualTo(other: UIEdgeInsets) -> Constraint {
  212. return constrainTo(other, relation: .GreaterThanOrEqualTo)
  213. }
  214. // MARK: multiplier
  215. func multipliedBy(amount: Float) -> Constraint {
  216. self.multiplier = amount
  217. return self
  218. }
  219. func dividedBy(amount: Float) -> Constraint {
  220. self.multiplier = 1.0 / amount;
  221. return self
  222. }
  223. // MARK: priority
  224. func priority(priority: Float) -> Constraint {
  225. self.priority = priority
  226. return self
  227. }
  228. func priorityRequired() -> Constraint {
  229. return priority(1000.0)
  230. }
  231. func priorityHigh() -> Constraint {
  232. return priority(750.0)
  233. }
  234. func priorityLow() -> Constraint {
  235. return priority(250.0)
  236. }
  237. // MARK: offset
  238. func offset(amount: Float) -> Constraint {
  239. self.offset = amount
  240. return self
  241. }
  242. func offset(amount: Int) -> Constraint {
  243. self.offset = amount
  244. return self
  245. }
  246. func offset(amount: CGPoint) -> Constraint {
  247. self.offset = amount
  248. return self
  249. }
  250. func offset(amount: CGSize) -> Constraint {
  251. self.offset = amount
  252. return self
  253. }
  254. func offset(amount: UIEdgeInsets) -> Constraint {
  255. self.offset = amount
  256. return self
  257. }
  258. // MARK: insets
  259. func insets(amount: UIEdgeInsets) -> Constraint {
  260. self.offset = amount
  261. return self
  262. }
  263. // MARK: install
  264. func install() -> Array<LayoutConstraint> {
  265. var installOnView: View? = nil
  266. if self.toItem.view {
  267. installOnView = Constraint.closestCommonSuperviewFromView(self.fromItem.view, toView: self.toItem.view)
  268. if !installOnView {
  269. NSException(name: "Cannot Install Constraint", reason: "No common superview between views", userInfo: nil).raise()
  270. return []
  271. }
  272. } else {
  273. installOnView = self.fromItem.view?.superview
  274. if !installOnView {
  275. NSException(name: "Cannot Install Constraint", reason: "Missing superview", userInfo: nil).raise()
  276. return []
  277. }
  278. }
  279. var layoutConstraints: Array<LayoutConstraint> = []
  280. let layoutFromAttributes = self.fromItem.attributes.layoutAttributes
  281. let layoutToAttributes = self.toItem.attributes.layoutAttributes
  282. // get layout from
  283. let layoutFrom: View? = self.fromItem.view
  284. // get layout to
  285. let layoutTo: View? = self.toItem.view
  286. // get layout relation
  287. let layoutRelation: NSLayoutRelation = (self.relation) ? self.relation!.layoutRelation : .Equal
  288. for layoutFromAttribute in layoutFromAttributes {
  289. // get layout to attribute
  290. let layoutToAttribute = (layoutToAttributes.count > 0) ? layoutToAttributes[0] : layoutFromAttribute
  291. // get layout constant
  292. var layoutConstant: CGFloat = layoutToAttribute.snp_constantForValue(self.constant)
  293. layoutConstant += layoutToAttribute.snp_offsetForValue(self.offset)
  294. // create layout constraint
  295. let layoutConstraint = LayoutConstraint(
  296. item: layoutFrom,
  297. attribute: layoutFromAttribute,
  298. relatedBy: layoutRelation,
  299. toItem: layoutTo,
  300. attribute: layoutToAttribute,
  301. multiplier: CGFloat(self.multiplier),
  302. constant: layoutConstant)
  303. // set priority
  304. layoutConstraint.priority = self.priority
  305. // set constraint
  306. layoutConstraint.constraint = self
  307. layoutConstraints.append(layoutConstraint)
  308. }
  309. installOnView?.addConstraints(layoutConstraints)
  310. self.installedOnView = installOnView
  311. return layoutConstraints
  312. }
  313. // MARK: uninstall
  314. func uninstall() {
  315. if let view = self.installedOnView {
  316. var installedConstraints = view.constraints()
  317. var constraintsToRemove: Array<LayoutConstraint> = []
  318. for installedConstraint in installedConstraints {
  319. if let layoutConstraint = installedConstraint as? LayoutConstraint {
  320. if layoutConstraint.constraint === self {
  321. constraintsToRemove.append(layoutConstraint)
  322. }
  323. }
  324. }
  325. if constraintsToRemove.count > 0 {
  326. view.removeConstraints(constraintsToRemove)
  327. }
  328. }
  329. self.installedOnView = nil
  330. }
  331. // MARK: private
  332. private let fromItem: ConstraintItem
  333. private var toItem: ConstraintItem
  334. private var relation: ConstraintRelation?
  335. private var constant: Any?
  336. private var multiplier: Float = 1.0
  337. private var priority: Float = 1000.0
  338. private var offset: Any?
  339. private var insets: UIEdgeInsets = UIEdgeInsetsZero
  340. private weak var installedOnView: View?
  341. private func addConstraint(attributes: ConstraintAttributes) -> Constraint {
  342. if !self.relation {
  343. self.fromItem.attributes += attributes
  344. }
  345. return self
  346. }
  347. private func constrainTo(other: ConstraintItem, relation: ConstraintRelation) -> Constraint {
  348. if other.attributes != ConstraintAttributes.None {
  349. var toLayoutAttributes = other.attributes.layoutAttributes
  350. if toLayoutAttributes.count > 1 {
  351. var fromLayoutAttributes = self.fromItem.attributes.layoutAttributes
  352. if toLayoutAttributes != fromLayoutAttributes {
  353. NSException(name: "Invalid Constraint", reason: "Cannot constrain to multiple non identical attributes", userInfo: nil).raise()
  354. return self
  355. }
  356. other.attributes = ConstraintAttributes.None
  357. }
  358. }
  359. self.toItem = other
  360. self.relation = relation
  361. return self
  362. }
  363. private func constrainTo(other: View, relation: ConstraintRelation) -> Constraint {
  364. return constrainTo(ConstraintItem(view: other, attributes: ConstraintAttributes.None), relation: relation)
  365. }
  366. private func constrainTo(other: Float, relation: ConstraintRelation) -> Constraint {
  367. self.constant = other
  368. return constrainTo(ConstraintItem(view: nil, attributes: ConstraintAttributes.None), relation: relation)
  369. }
  370. private func constrainTo(other: CGSize, relation: ConstraintRelation) -> Constraint {
  371. self.constant = other
  372. return constrainTo(ConstraintItem(view: nil, attributes: ConstraintAttributes.None), relation: relation)
  373. }
  374. private func constrainTo(other: CGPoint, relation: ConstraintRelation) -> Constraint {
  375. self.constant = other
  376. return constrainTo(ConstraintItem(view: nil, attributes: ConstraintAttributes.None), relation: relation)
  377. }
  378. private func constrainTo(other: UIEdgeInsets, relation: ConstraintRelation) -> Constraint {
  379. self.constant = other
  380. return constrainTo(ConstraintItem(view: nil, attributes: ConstraintAttributes.None), relation: relation)
  381. }
  382. private class func closestCommonSuperviewFromView(fromView: View?, toView: View?) -> View? {
  383. var closestCommonSuperview: View?
  384. var secondViewSuperview: View? = toView
  385. while !closestCommonSuperview && secondViewSuperview {
  386. var firstViewSuperview = fromView
  387. while !closestCommonSuperview && firstViewSuperview {
  388. if secondViewSuperview == firstViewSuperview {
  389. closestCommonSuperview = secondViewSuperview
  390. }
  391. firstViewSuperview = firstViewSuperview?.superview
  392. }
  393. secondViewSuperview = secondViewSuperview?.superview
  394. }
  395. return closestCommonSuperview
  396. }
  397. }
  398. private extension NSLayoutAttribute {
  399. func snp_offsetForValue(value: Any?) -> CGFloat {
  400. // Float
  401. if let float = value as? Float {
  402. return CGFloat(float)
  403. }
  404. // Int
  405. else if let int = value as? Int {
  406. return CGFloat(int)
  407. }
  408. // CGFloat
  409. else if let float = value as? CGFloat {
  410. return float
  411. }
  412. // CGSize
  413. else if let size = value as? CGSize {
  414. if self == .Width {
  415. return size.width
  416. } else if self == .Height {
  417. return size.height
  418. }
  419. }
  420. // CGPoint
  421. else if let point = value as? CGPoint {
  422. if self == .Left || self == .CenterX {
  423. return point.x
  424. } else if self == .Top || self == .CenterY {
  425. return point.y
  426. } else if self == .Right {
  427. return -point.x
  428. } else if self == .Bottom {
  429. return -point.y
  430. }
  431. }
  432. // UIEdgeInsets
  433. else if let insets = value as? UIEdgeInsets {
  434. if self == .Left {
  435. return insets.left
  436. } else if self == .Top {
  437. return insets.top
  438. } else if self == .Right {
  439. return -insets.right
  440. } else if self == .Bottom {
  441. return -insets.bottom
  442. }
  443. }
  444. return CGFloat(0)
  445. }
  446. func snp_constantForValue(value: Any?) -> CGFloat {
  447. // Float
  448. if let float = value as? Float {
  449. return CGFloat(float)
  450. }
  451. // Int
  452. else if let int = value as? Int {
  453. return CGFloat(int)
  454. }
  455. // CGFloat
  456. else if let float = value as? CGFloat {
  457. return float
  458. }
  459. // CGSize
  460. else if let size = value as? CGSize {
  461. if self == .Width {
  462. return size.width
  463. } else if self == .Height {
  464. return size.height
  465. }
  466. }
  467. // CGPoint
  468. else if let point = value as? CGPoint {
  469. if self == .Left || self == .CenterX {
  470. return point.x
  471. } else if self == .Top || self == .CenterY {
  472. return point.y
  473. } else if self == .Right {
  474. return point.x
  475. } else if self == .Bottom {
  476. return point.y
  477. }
  478. }
  479. // UIEdgeInsets
  480. else if let insets = value as? UIEdgeInsets {
  481. if self == .Left {
  482. return insets.left
  483. } else if self == .Top {
  484. return insets.top
  485. } else if self == .Right {
  486. return insets.right
  487. } else if self == .Bottom {
  488. return insets.bottom
  489. }
  490. }
  491. return CGFloat(0);
  492. }
  493. }