Constraint.swift 19 KB

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