Constraint.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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. @objc(SnapKitConstraint)
  29. public final class Constraint : NSObject {
  30. internal let sourceLocation: (String, UInt)
  31. internal let label: String?
  32. private let from: ConstraintItem
  33. private let to: ConstraintItem
  34. private let relation: ConstraintRelation
  35. private let multiplier: ConstraintMultiplierTarget
  36. private var constant: ConstraintConstantTarget {
  37. didSet {
  38. self.updateConstantAndPriorityIfNeeded()
  39. }
  40. }
  41. private var priority: ConstraintPriorityTarget {
  42. didSet {
  43. self.updateConstantAndPriorityIfNeeded()
  44. }
  45. }
  46. private var layoutConstraints: [LayoutConstraint]
  47. // MARK: Initialization
  48. internal init(from: ConstraintItem,
  49. to: ConstraintItem,
  50. relation: ConstraintRelation,
  51. sourceLocation: (String, UInt),
  52. label: String?,
  53. multiplier: ConstraintMultiplierTarget,
  54. constant: ConstraintConstantTarget,
  55. priority: ConstraintPriorityTarget) {
  56. self.from = from
  57. self.to = to
  58. self.relation = relation
  59. self.sourceLocation = sourceLocation
  60. self.label = label
  61. self.multiplier = multiplier
  62. self.constant = constant
  63. self.priority = priority
  64. self.layoutConstraints = []
  65. super.init()
  66. // get attributes
  67. let layoutFromAttributes = self.from.attributes.layoutAttributes
  68. let layoutToAttributes = self.to.attributes.layoutAttributes
  69. // get layout from
  70. let layoutFrom = self.from.layoutConstraintItem!
  71. // get relation
  72. let layoutRelation = self.relation.layoutRelation
  73. for layoutFromAttribute in layoutFromAttributes {
  74. // get layout to attribute
  75. let layoutToAttribute: NSLayoutAttribute
  76. #if os(iOS) || os(tvOS)
  77. if layoutToAttributes.count > 0 {
  78. if self.from.attributes == .edges && self.to.attributes == .margins {
  79. switch layoutFromAttribute {
  80. case .left:
  81. layoutToAttribute = .leftMargin
  82. case .right:
  83. layoutToAttribute = .rightMargin
  84. case .top:
  85. layoutToAttribute = .topMargin
  86. case .bottom:
  87. layoutToAttribute = .bottomMargin
  88. default:
  89. fatalError()
  90. }
  91. } else if self.from.attributes == .margins && self.to.attributes == .edges {
  92. switch layoutFromAttribute {
  93. case .leftMargin:
  94. layoutToAttribute = .left
  95. case .rightMargin:
  96. layoutToAttribute = .right
  97. case .topMargin:
  98. layoutToAttribute = .top
  99. case .bottomMargin:
  100. layoutToAttribute = .bottom
  101. default:
  102. fatalError()
  103. }
  104. } else if self.from.attributes == self.to.attributes {
  105. layoutToAttribute = layoutFromAttribute
  106. } else {
  107. layoutToAttribute = layoutToAttributes[0]
  108. }
  109. } else {
  110. if self.to.target == nil && (layoutFromAttribute == .centerX || layoutFromAttribute == .centerY) {
  111. layoutToAttribute = layoutFromAttribute == .centerX ? .left : .top
  112. } else {
  113. layoutToAttribute = layoutFromAttribute
  114. }
  115. }
  116. #else
  117. if self.from.attributes == self.to.attributes {
  118. layoutToAttribute = layoutFromAttribute
  119. } else if layoutToAttributes.count > 0 {
  120. layoutToAttribute = layoutToAttributes[0]
  121. } else {
  122. layoutToAttribute = layoutFromAttribute
  123. }
  124. #endif
  125. // get layout constant
  126. let layoutConstant: CGFloat = self.constant.constraintConstantTargetValueFor(layoutAttribute: layoutToAttribute)
  127. // get layout to
  128. var layoutTo: AnyObject? = self.to.target
  129. // use superview if possible
  130. if layoutTo == nil && layoutToAttribute != .width && layoutToAttribute != .height {
  131. layoutTo = layoutFrom.superview
  132. }
  133. // create layout constraint
  134. let layoutConstraint = LayoutConstraint(
  135. item: layoutFrom,
  136. attribute: layoutFromAttribute,
  137. relatedBy: layoutRelation,
  138. toItem: layoutTo,
  139. attribute: layoutToAttribute,
  140. multiplier: self.multiplier.constraintMultiplierTargetValue,
  141. constant: layoutConstant
  142. )
  143. // set label
  144. layoutConstraint.label = self.label
  145. // set priority
  146. layoutConstraint.priority = self.priority.constraintPriorityTargetValue
  147. // set constraint
  148. layoutConstraint.constraint = self
  149. // append
  150. self.layoutConstraints.append(layoutConstraint)
  151. }
  152. }
  153. // MARK: Public
  154. @available(*, deprecated:3.0, message:"Use activate().")
  155. public func install() {
  156. self.activate()
  157. }
  158. @available(*, deprecated:3.0, message:"Use deactivate().")
  159. public func uninstall() {
  160. self.deactivate()
  161. }
  162. public func activate() {
  163. self.activateIfNeeded()
  164. }
  165. public func deactivate() {
  166. self.deactivateIfNeeded()
  167. }
  168. @discardableResult
  169. public func update(offset: ConstraintOffsetTarget) -> Constraint {
  170. self.constant = offset.constraintOffsetTargetValue
  171. return self
  172. }
  173. @discardableResult
  174. public func update(inset: ConstraintInsetTarget) -> Constraint {
  175. self.constant = inset.constraintInsetTargetValue
  176. return self
  177. }
  178. @discardableResult
  179. public func update(priority: ConstraintPriorityTarget) -> Constraint {
  180. self.priority = priority.constraintPriorityTargetValue
  181. return self
  182. }
  183. @available(*, deprecated:3.0, message:"Use update(offset: ConstraintOffsetTarget) instead.")
  184. public func updateOffset(amount: ConstraintOffsetTarget) -> Void { self.update(offset: amount) }
  185. @available(*, deprecated:3.0, message:"Use update(inset: ConstraintInsetTarget) instead.")
  186. public func updateInsets(amount: ConstraintInsetTarget) -> Void { self.update(inset: amount) }
  187. @available(*, deprecated:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
  188. public func updatePriority(amount: ConstraintPriorityTarget) -> Void { self.update(priority: amount) }
  189. @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
  190. public func updatePriorityRequired() -> Void {}
  191. @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
  192. public func updatePriorityHigh() -> Void { fatalError("Must be implemented by Concrete subclass.") }
  193. @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
  194. public func updatePriorityMedium() -> Void { fatalError("Must be implemented by Concrete subclass.") }
  195. @available(*, obsoleted:3.0, message:"Use update(priority: ConstraintPriorityTarget) instead.")
  196. public func updatePriorityLow() -> Void { fatalError("Must be implemented by Concrete subclass.") }
  197. // MARK: Internal
  198. internal func updateConstantAndPriorityIfNeeded() {
  199. for layoutConstraint in self.layoutConstraints {
  200. let attribute = (layoutConstraint.secondAttribute == .notAnAttribute) ? layoutConstraint.firstAttribute : layoutConstraint.secondAttribute
  201. layoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: attribute)
  202. #if os(iOS) || os(tvOS)
  203. let requiredPriority: UILayoutPriority = UILayoutPriorityRequired
  204. #else
  205. let requiredPriority: Float = 1000.0
  206. #endif
  207. if (layoutConstraint.priority < requiredPriority), (self.priority.constraintPriorityTargetValue != requiredPriority) {
  208. layoutConstraint.priority = self.priority.constraintPriorityTargetValue
  209. }
  210. }
  211. }
  212. internal func activateIfNeeded(updatingExisting: Bool = false) {
  213. guard let item = self.from.layoutConstraintItem else {
  214. print("WARNING: SnapKit failed to get from item from constraint. Activate will be a no-op.")
  215. return
  216. }
  217. let layoutConstraints = self.layoutConstraints
  218. if updatingExisting {
  219. var existingLayoutConstraints: [LayoutConstraint] = []
  220. for constraint in item.constraints {
  221. existingLayoutConstraints += constraint.layoutConstraints
  222. }
  223. for layoutConstraint in layoutConstraints {
  224. let existingLayoutConstraint = existingLayoutConstraints.first { $0 == layoutConstraint }
  225. guard let updateLayoutConstraint = existingLayoutConstraint else {
  226. fatalError("Updated constraint could not find existing matching constraint to update: \(layoutConstraint)")
  227. }
  228. let updateLayoutAttribute = (updateLayoutConstraint.secondAttribute == .notAnAttribute) ? updateLayoutConstraint.firstAttribute : updateLayoutConstraint.secondAttribute
  229. updateLayoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: updateLayoutAttribute)
  230. }
  231. } else {
  232. NSLayoutConstraint.activate(layoutConstraints)
  233. item.add(constraints: [self])
  234. }
  235. }
  236. internal func deactivateIfNeeded() {
  237. guard let item = self.from.layoutConstraintItem else {
  238. print("WARNING: SnapKit failed to get from item from constraint. Deactivate will be a no-op.")
  239. return
  240. }
  241. let layoutConstraints = self.layoutConstraints
  242. NSLayoutConstraint.deactivate(layoutConstraints)
  243. item.remove(constraints: [self])
  244. }
  245. }