Constraint.swift 19 KB

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