Constraint.swift 20 KB

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