Constraint.swift 20 KB

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