Constraint.swift 19 KB

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