Constraint.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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 to
  293. let layoutTo: View? = self.toItem.view
  294. // get layout relation
  295. let layoutRelation: NSLayoutRelation = (self.relation != nil) ? self.relation!.layoutRelation : .Equal
  296. for layoutFromAttribute in layoutFromAttributes {
  297. // get layout to attribute
  298. let layoutToAttribute = (layoutToAttributes.count > 0) ? layoutToAttributes[0] : layoutFromAttribute
  299. // get layout constant
  300. var layoutConstant: CGFloat = layoutToAttribute.snp_constantForValue(self.constant)
  301. layoutConstant += layoutToAttribute.snp_offsetForValue(self.offset)
  302. // create layout constraint
  303. let layoutConstraint = LayoutConstraint(
  304. item: layoutFrom,
  305. attribute: layoutFromAttribute,
  306. relatedBy: layoutRelation,
  307. toItem: layoutTo,
  308. attribute: layoutToAttribute,
  309. multiplier: CGFloat(self.multiplier),
  310. constant: layoutConstant)
  311. // set priority
  312. layoutConstraint.priority = self.priority
  313. // set constraint
  314. layoutConstraint.constraint = self
  315. layoutConstraints.append(layoutConstraint)
  316. }
  317. installOnView?.addConstraints(layoutConstraints)
  318. self.installedOnView = installOnView
  319. return layoutConstraints
  320. }
  321. // MARK: uninstall
  322. func uninstall() {
  323. if let view = self.installedOnView {
  324. #if os(iOS)
  325. var installedConstraints = view.constraints()
  326. #else
  327. var installedConstraints = view.constraints
  328. #endif
  329. var constraintsToRemove: Array<LayoutConstraint> = []
  330. for installedConstraint in installedConstraints {
  331. if let layoutConstraint = installedConstraint as? LayoutConstraint {
  332. if layoutConstraint.constraint === self {
  333. constraintsToRemove.append(layoutConstraint)
  334. }
  335. }
  336. }
  337. if constraintsToRemove.count > 0 {
  338. view.removeConstraints(constraintsToRemove)
  339. }
  340. }
  341. self.installedOnView = nil
  342. }
  343. // MARK: private
  344. private let fromItem: ConstraintItem
  345. private var toItem: ConstraintItem
  346. private var relation: ConstraintRelation?
  347. private var constant: Any?
  348. private var multiplier: Float = 1.0
  349. private var priority: Float = 1000.0
  350. private var offset: Any?
  351. private weak var installedOnView: View?
  352. private func addConstraint(attributes: ConstraintAttributes) -> Constraint {
  353. if self.relation == nil {
  354. self.fromItem.attributes += attributes
  355. }
  356. return self
  357. }
  358. private func constrainTo(other: ConstraintItem, relation: ConstraintRelation) -> Constraint {
  359. if other.attributes != ConstraintAttributes.None {
  360. var toLayoutAttributes = other.attributes.layoutAttributes
  361. if toLayoutAttributes.count > 1 {
  362. var fromLayoutAttributes = self.fromItem.attributes.layoutAttributes
  363. if toLayoutAttributes != fromLayoutAttributes {
  364. NSException(name: "Invalid Constraint", reason: "Cannot constrain to multiple non identical attributes", userInfo: nil).raise()
  365. return self
  366. }
  367. other.attributes = ConstraintAttributes.None
  368. }
  369. }
  370. self.toItem = other
  371. self.relation = relation
  372. return self
  373. }
  374. private func constrainTo(other: View, relation: ConstraintRelation) -> Constraint {
  375. return constrainTo(ConstraintItem(view: other, attributes: ConstraintAttributes.None), relation: relation)
  376. }
  377. private func constrainTo(other: Float, relation: ConstraintRelation) -> Constraint {
  378. self.constant = other
  379. return constrainTo(ConstraintItem(view: nil, attributes: ConstraintAttributes.None), relation: relation)
  380. }
  381. private func constrainTo(other: CGSize, relation: ConstraintRelation) -> Constraint {
  382. self.constant = other
  383. return constrainTo(ConstraintItem(view: nil, attributes: ConstraintAttributes.None), relation: relation)
  384. }
  385. private func constrainTo(other: CGPoint, relation: ConstraintRelation) -> Constraint {
  386. self.constant = other
  387. return constrainTo(ConstraintItem(view: nil, attributes: ConstraintAttributes.None), relation: relation)
  388. }
  389. private func constrainTo(other: EdgeInsets, relation: ConstraintRelation) -> Constraint {
  390. self.constant = other
  391. return constrainTo(ConstraintItem(view: nil, attributes: ConstraintAttributes.None), relation: relation)
  392. }
  393. private class func closestCommonSuperviewFromView(fromView: View?, toView: View?) -> View? {
  394. var closestCommonSuperview: View?
  395. var secondViewSuperview: View? = toView
  396. while closestCommonSuperview == nil && secondViewSuperview != nil {
  397. var firstViewSuperview = fromView
  398. while closestCommonSuperview == nil && firstViewSuperview != nil {
  399. if secondViewSuperview == firstViewSuperview {
  400. closestCommonSuperview = secondViewSuperview
  401. }
  402. firstViewSuperview = firstViewSuperview?.superview
  403. }
  404. secondViewSuperview = secondViewSuperview?.superview
  405. }
  406. return closestCommonSuperview
  407. }
  408. }
  409. private extension NSLayoutAttribute {
  410. func snp_offsetForValue(value: Any?) -> CGFloat {
  411. // Float
  412. if let float = value as? Float {
  413. return CGFloat(float)
  414. }
  415. // Int
  416. else if let int = value as? Int {
  417. return CGFloat(int)
  418. }
  419. // CGFloat
  420. else if let float = value as? CGFloat {
  421. return float
  422. }
  423. // CGSize
  424. else if let size = value as? CGSize {
  425. if self == .Width {
  426. return size.width
  427. } else if self == .Height {
  428. return size.height
  429. }
  430. }
  431. // CGPoint
  432. else if let point = value as? CGPoint {
  433. if self == .Left || self == .CenterX {
  434. return point.x
  435. } else if self == .Top || self == .CenterY {
  436. return point.y
  437. } else if self == .Right {
  438. return -point.x
  439. } else if self == .Bottom {
  440. return -point.y
  441. }
  442. }
  443. // EdgeInsets
  444. else if let insets = value as? EdgeInsets {
  445. if self == .Left {
  446. return insets.left
  447. } else if self == .Top {
  448. return insets.top
  449. } else if self == .Right {
  450. return -insets.right
  451. } else if self == .Bottom {
  452. return -insets.bottom
  453. }
  454. }
  455. return CGFloat(0)
  456. }
  457. func snp_constantForValue(value: Any?) -> CGFloat {
  458. // Float
  459. if let float = value as? Float {
  460. return CGFloat(float)
  461. }
  462. // Int
  463. else if let int = value as? Int {
  464. return CGFloat(int)
  465. }
  466. // CGFloat
  467. else if let float = value as? CGFloat {
  468. return float
  469. }
  470. // CGSize
  471. else if let size = value as? CGSize {
  472. if self == .Width {
  473. return size.width
  474. } else if self == .Height {
  475. return size.height
  476. }
  477. }
  478. // CGPoint
  479. else if let point = value as? CGPoint {
  480. if self == .Left || self == .CenterX {
  481. return point.x
  482. } else if self == .Top || self == .CenterY {
  483. return point.y
  484. } else if self == .Right {
  485. return point.x
  486. } else if self == .Bottom {
  487. return point.y
  488. }
  489. }
  490. // EdgeInsets
  491. else if let insets = value as? EdgeInsets {
  492. if self == .Left {
  493. return insets.left
  494. } else if self == .Top {
  495. return insets.top
  496. } else if self == .Right {
  497. return insets.right
  498. } else if self == .Bottom {
  499. return insets.bottom
  500. }
  501. }
  502. return CGFloat(0);
  503. }
  504. }