Constraint.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. //
  2. // SnapKit
  3. //
  4. // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. #if os(iOS) || os(tvOS)
  24. import UIKit
  25. #else
  26. import AppKit
  27. #endif
  28. public class Constraint {
  29. internal let sourceLocation: (String, UInt)
  30. internal let label: String?
  31. private let from: ConstraintItem
  32. private let to: ConstraintItem
  33. private let relation: ConstraintRelation
  34. private let multiplier: ConstraintMultiplierTarget
  35. private var constant: ConstraintConstantTarget {
  36. didSet {
  37. self.updateConstantAndPriorityIfNeeded()
  38. }
  39. }
  40. private var priority: ConstraintPriorityTarget {
  41. didSet {
  42. self.updateConstantAndPriorityIfNeeded()
  43. }
  44. }
  45. private var layoutConstraints: [LayoutConstraint]
  46. // MARK: Initialization
  47. internal init(from: ConstraintItem,
  48. to: ConstraintItem,
  49. relation: ConstraintRelation,
  50. sourceLocation: (String, UInt),
  51. label: String?,
  52. multiplier: ConstraintMultiplierTarget,
  53. constant: ConstraintConstantTarget,
  54. priority: ConstraintPriorityTarget) {
  55. self.from = from
  56. self.to = to
  57. self.relation = relation
  58. self.sourceLocation = sourceLocation
  59. self.label = label
  60. self.multiplier = multiplier
  61. self.constant = constant
  62. self.priority = priority
  63. self.layoutConstraints = []
  64. // get attributes
  65. let layoutFromAttributes = self.from.attributes.layoutAttributes
  66. let layoutToAttributes = self.to.attributes.layoutAttributes
  67. // get layout from
  68. let layoutFrom: ConstraintView = self.from.view!
  69. // get relation
  70. let layoutRelation = self.relation.layoutRelation
  71. for layoutFromAttribute in layoutFromAttributes {
  72. // get layout to attribute
  73. let layoutToAttribute: NSLayoutAttribute
  74. #if os(iOS) || os(tvOS)
  75. if layoutToAttributes.count > 0 {
  76. if self.from.attributes == .edges && self.to.attributes == .margins {
  77. switch layoutFromAttribute {
  78. case .left:
  79. layoutToAttribute = .leftMargin
  80. case .right:
  81. layoutToAttribute = .rightMargin
  82. case .top:
  83. layoutToAttribute = .topMargin
  84. case .bottom:
  85. layoutToAttribute = .bottomMargin
  86. default:
  87. fatalError()
  88. }
  89. } else if self.from.attributes == .margins && self.to.attributes == .edges {
  90. switch layoutFromAttribute {
  91. case .leftMargin:
  92. layoutToAttribute = .left
  93. case .rightMargin:
  94. layoutToAttribute = .right
  95. case .topMargin:
  96. layoutToAttribute = .top
  97. case .bottomMargin:
  98. layoutToAttribute = .bottom
  99. default:
  100. fatalError()
  101. }
  102. } else if self.from.attributes == self.to.attributes {
  103. layoutToAttribute = layoutFromAttribute
  104. } else {
  105. layoutToAttribute = layoutToAttributes[0]
  106. }
  107. } else {
  108. if self.to.target == nil && (layoutFromAttribute == .centerX || layoutFromAttribute == .centerY) {
  109. layoutToAttribute = layoutFromAttribute == .centerX ? .left : .top
  110. } else {
  111. layoutToAttribute = layoutFromAttribute
  112. }
  113. }
  114. #else
  115. if self.from.attributes == self.to.attributes {
  116. layoutToAttribute = layoutFromAttribute
  117. } else if layoutToAttributes.count > 0 {
  118. layoutToAttribute = layoutToAttributes[0]
  119. } else {
  120. layoutToAttribute = layoutFromAttribute
  121. }
  122. #endif
  123. // get layout constant
  124. let layoutConstant: CGFloat = self.constant.constraintConstantTargetValueFor(layoutAttribute: layoutToAttribute)
  125. // get layout to
  126. var layoutTo: AnyObject? = self.to.target
  127. // use superview if possible
  128. if layoutTo == nil && layoutToAttribute != .width && layoutToAttribute != .height {
  129. layoutTo = layoutFrom.superview
  130. }
  131. // create layout constraint
  132. let layoutConstraint = LayoutConstraint(
  133. item: layoutFrom,
  134. attribute: layoutFromAttribute,
  135. relatedBy: layoutRelation,
  136. toItem: layoutTo,
  137. attribute: layoutToAttribute,
  138. multiplier: self.multiplier.constraintMultiplierTargetValue,
  139. constant: layoutConstant
  140. )
  141. // set label
  142. layoutConstraint.label = self.label
  143. // set priority
  144. layoutConstraint.priority = self.priority.constraintPriorityTargetValue
  145. // set constraint
  146. layoutConstraint.constraint = self
  147. // append
  148. self.layoutConstraints.append(layoutConstraint)
  149. }
  150. }
  151. // MARK: Public
  152. @available(*, deprecated:3.0, message:"Use activate().")
  153. public func install() {
  154. self.activate()
  155. }
  156. @available(*, deprecated:3.0, message:"Use deactivate().")
  157. public func uninstall() {
  158. self.deactivate()
  159. }
  160. public func activate() {
  161. self.activateIfNeeded()
  162. }
  163. public func deactivate() {
  164. self.deactivateIfNeeded()
  165. }
  166. @discardableResult
  167. public func update(offset: ConstraintOffsetTarget) -> Constraint {
  168. self.constant = offset.constraintOffsetTargetValue
  169. return self
  170. }
  171. @discardableResult
  172. public func update(inset: ConstraintInsetTarget) -> Constraint {
  173. self.constant = inset.constraintInsetTargetValue
  174. return self
  175. }
  176. @discardableResult
  177. public func update(priority: ConstraintPriorityTarget) -> Constraint {
  178. self.priority = priority.constraintPriorityTargetValue
  179. return self
  180. }
  181. @available(*, deprecated:3.0, message:"Use update(offset: ConstraintOffsetTarget) instead.")
  182. public func updateOffset(amount: ConstraintOffsetTarget) -> Void { self.update(offset: amount) }
  183. @available(*, deprecated:3.0, message:"Use update(inset: ConstraintInsetTarget) instead.")
  184. public func updateInsets(amount: ConstraintInsetTarget) -> Void { self.update(inset: amount) }
  185. @available(*, deprecated:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
  186. public func updatePriority(amount: ConstraintPriorityTarget) -> Void { self.update(priority: amount) }
  187. @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
  188. public func updatePriorityRequired() -> Void {}
  189. @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
  190. public func updatePriorityHigh() -> Void { fatalError("Must be implemented by Concrete subclass.") }
  191. @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
  192. public func updatePriorityMedium() -> Void { fatalError("Must be implemented by Concrete subclass.") }
  193. @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
  194. public func updatePriorityLow() -> Void { fatalError("Must be implemented by Concrete subclass.") }
  195. // MARK: Internal
  196. internal func updateConstantAndPriorityIfNeeded() {
  197. for layoutConstraint in self.layoutConstraints {
  198. let attribute = (layoutConstraint.secondAttribute == .notAnAttribute) ? layoutConstraint.firstAttribute : layoutConstraint.secondAttribute
  199. layoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: attribute)
  200. #if os(iOS) || os(tvOS)
  201. let requiredPriority: UILayoutPriority = UILayoutPriorityRequired
  202. #else
  203. let requiredPriority: Float = 1000.0
  204. #endif
  205. if (layoutConstraint.priority < requiredPriority), (self.priority.constraintPriorityTargetValue != requiredPriority) {
  206. layoutConstraint.priority = self.priority.constraintPriorityTargetValue
  207. }
  208. }
  209. }
  210. internal func activateIfNeeded(updatingExisting: Bool = false) {
  211. guard let view = self.from.view else {
  212. print("WARNING: SnapKit failed to get from view from constraint. Activate will be a no-op.")
  213. return
  214. }
  215. let layoutConstraints = self.layoutConstraints
  216. let existingLayoutConstraints = view.snp.constraints.map({ $0.layoutConstraints }).reduce([]) { $0 + $1 }
  217. if updatingExisting {
  218. for layoutConstraint in layoutConstraints {
  219. let existingLayoutConstraint = existingLayoutConstraints.first { $0 == layoutConstraint }
  220. guard let updateLayoutConstraint = existingLayoutConstraint else {
  221. fatalError("Updated constraint could not find existing matching constraint to update: \(layoutConstraint)")
  222. }
  223. let updateLayoutAttribute = (updateLayoutConstraint.secondAttribute == .notAnAttribute) ? updateLayoutConstraint.firstAttribute : updateLayoutConstraint.secondAttribute
  224. updateLayoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: updateLayoutAttribute)
  225. }
  226. } else {
  227. NSLayoutConstraint.activate(layoutConstraints)
  228. view.snp.add(constraints: [self])
  229. }
  230. }
  231. internal func deactivateIfNeeded() {
  232. guard let view = self.from.view else {
  233. print("WARNING: SnapKit failed to get from view from constraint. Deactivate will be a no-op.")
  234. return
  235. }
  236. let layoutConstraints = self.layoutConstraints
  237. NSLayoutConstraint.deactivate(layoutConstraints)
  238. view.snp.remove(constraints: [self])
  239. }
  240. }