Constraint.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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 final 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. public var layoutConstraints: [LayoutConstraint]
  46. public var isActive: Bool {
  47. set {
  48. if newValue {
  49. activate()
  50. }
  51. else {
  52. deactivate()
  53. }
  54. }
  55. get {
  56. for layoutConstraint in self.layoutConstraints {
  57. if layoutConstraint.isActive {
  58. return true
  59. }
  60. }
  61. return false
  62. }
  63. }
  64. // MARK: Initialization
  65. internal init(from: ConstraintItem,
  66. to: ConstraintItem,
  67. relation: ConstraintRelation,
  68. sourceLocation: (String, UInt),
  69. label: String?,
  70. multiplier: ConstraintMultiplierTarget,
  71. constant: ConstraintConstantTarget,
  72. priority: ConstraintPriorityTarget) {
  73. self.from = from
  74. self.to = to
  75. self.relation = relation
  76. self.sourceLocation = sourceLocation
  77. self.label = label
  78. self.multiplier = multiplier
  79. self.constant = constant
  80. self.priority = priority
  81. self.layoutConstraints = []
  82. // get attributes
  83. let layoutFromAttributes = self.from.attributes.layoutAttributes
  84. let layoutToAttributes = self.to.attributes.layoutAttributes
  85. // get layout from
  86. let layoutFrom = self.from.layoutConstraintItem!
  87. // get relation
  88. let layoutRelation = self.relation.layoutRelation
  89. for layoutFromAttribute in layoutFromAttributes {
  90. // get layout to attribute
  91. let layoutToAttribute: LayoutAttribute
  92. #if os(iOS) || os(tvOS)
  93. if layoutToAttributes.count > 0 {
  94. if self.from.attributes == .edges && self.to.attributes == .margins {
  95. switch layoutFromAttribute {
  96. case .left:
  97. layoutToAttribute = .leftMargin
  98. case .right:
  99. layoutToAttribute = .rightMargin
  100. case .top:
  101. layoutToAttribute = .topMargin
  102. case .bottom:
  103. layoutToAttribute = .bottomMargin
  104. default:
  105. fatalError()
  106. }
  107. } else if self.from.attributes == .margins && self.to.attributes == .edges {
  108. switch layoutFromAttribute {
  109. case .leftMargin:
  110. layoutToAttribute = .left
  111. case .rightMargin:
  112. layoutToAttribute = .right
  113. case .topMargin:
  114. layoutToAttribute = .top
  115. case .bottomMargin:
  116. layoutToAttribute = .bottom
  117. default:
  118. fatalError()
  119. }
  120. } else if self.from.attributes == .directionalEdges && self.to.attributes == .directionalMargins {
  121. switch layoutFromAttribute {
  122. case .leading:
  123. layoutToAttribute = .leadingMargin
  124. case .trailing:
  125. layoutToAttribute = .trailingMargin
  126. case .top:
  127. layoutToAttribute = .topMargin
  128. case .bottom:
  129. layoutToAttribute = .bottomMargin
  130. default:
  131. fatalError()
  132. }
  133. } else if self.from.attributes == .directionalMargins && self.to.attributes == .directionalEdges {
  134. switch layoutFromAttribute {
  135. case .leadingMargin:
  136. layoutToAttribute = .leading
  137. case .trailingMargin:
  138. layoutToAttribute = .trailing
  139. case .topMargin:
  140. layoutToAttribute = .top
  141. case .bottomMargin:
  142. layoutToAttribute = .bottom
  143. default:
  144. fatalError()
  145. }
  146. } else if self.from.attributes == self.to.attributes {
  147. layoutToAttribute = layoutFromAttribute
  148. } else {
  149. layoutToAttribute = layoutToAttributes[0]
  150. }
  151. } else {
  152. if self.to.target == nil && (layoutFromAttribute == .centerX || layoutFromAttribute == .centerY) {
  153. layoutToAttribute = layoutFromAttribute == .centerX ? .left : .top
  154. } else {
  155. layoutToAttribute = layoutFromAttribute
  156. }
  157. }
  158. #else
  159. if self.from.attributes == self.to.attributes {
  160. layoutToAttribute = layoutFromAttribute
  161. } else if layoutToAttributes.count > 0 {
  162. layoutToAttribute = layoutToAttributes[0]
  163. } else {
  164. layoutToAttribute = layoutFromAttribute
  165. }
  166. #endif
  167. // get layout constant
  168. let layoutConstant: CGFloat = self.constant.constraintConstantTargetValueFor(layoutAttribute: layoutToAttribute)
  169. // get layout to
  170. var layoutTo: AnyObject? = self.to.target
  171. // use superview if possible
  172. if layoutTo == nil && layoutToAttribute != .width && layoutToAttribute != .height {
  173. layoutTo = layoutFrom.superview
  174. }
  175. // create layout constraint
  176. let layoutConstraint = LayoutConstraint(
  177. item: layoutFrom,
  178. attribute: layoutFromAttribute,
  179. relatedBy: layoutRelation,
  180. toItem: layoutTo,
  181. attribute: layoutToAttribute,
  182. multiplier: self.multiplier.constraintMultiplierTargetValue,
  183. constant: layoutConstant
  184. )
  185. // set label
  186. layoutConstraint.label = self.label
  187. // set priority
  188. layoutConstraint.priority = LayoutPriority(rawValue: self.priority.constraintPriorityTargetValue)
  189. // set constraint
  190. layoutConstraint.constraint = self
  191. // append
  192. self.layoutConstraints.append(layoutConstraint)
  193. }
  194. }
  195. // MARK: Public
  196. @available(*, deprecated, renamed:"activate()")
  197. public func install() {
  198. self.activate()
  199. }
  200. @available(*, deprecated, renamed:"deactivate()")
  201. public func uninstall() {
  202. self.deactivate()
  203. }
  204. public func activate() {
  205. self.activateIfNeeded()
  206. }
  207. public func deactivate() {
  208. self.deactivateIfNeeded()
  209. }
  210. @discardableResult
  211. public func update(offset: ConstraintOffsetTarget) -> Constraint {
  212. self.constant = offset.constraintOffsetTargetValue
  213. return self
  214. }
  215. @discardableResult
  216. public func update(inset: ConstraintInsetTarget) -> Constraint {
  217. self.constant = inset.constraintInsetTargetValue
  218. return self
  219. }
  220. #if os(iOS) || os(tvOS)
  221. @discardableResult
  222. @available(iOS 11.0, tvOS 11.0, *)
  223. public func update(inset: ConstraintDirectionalInsetTarget) -> Constraint {
  224. self.constant = inset.constraintDirectionalInsetTargetValue
  225. return self
  226. }
  227. #endif
  228. @discardableResult
  229. public func update(priority: ConstraintPriorityTarget) -> Constraint {
  230. self.priority = priority.constraintPriorityTargetValue
  231. return self
  232. }
  233. @discardableResult
  234. public func update(priority: ConstraintPriority) -> Constraint {
  235. self.priority = priority.value
  236. return self
  237. }
  238. @available(*, deprecated, renamed:"update(offset:)")
  239. public func updateOffset(amount: ConstraintOffsetTarget) -> Void { self.update(offset: amount) }
  240. @available(*, deprecated, renamed:"update(inset:)")
  241. public func updateInsets(amount: ConstraintInsetTarget) -> Void { self.update(inset: amount) }
  242. @available(*, deprecated, renamed:"update(priority:)")
  243. public func updatePriority(amount: ConstraintPriorityTarget) -> Void { self.update(priority: amount) }
  244. @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.")
  245. public func updatePriorityRequired() -> Void {}
  246. @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.")
  247. public func updatePriorityHigh() -> Void { fatalError("Must be implemented by Concrete subclass.") }
  248. @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.")
  249. public func updatePriorityMedium() -> Void { fatalError("Must be implemented by Concrete subclass.") }
  250. @available(*, deprecated, message:"Use update(priority: ConstraintPriorityTarget) instead.")
  251. public func updatePriorityLow() -> Void { fatalError("Must be implemented by Concrete subclass.") }
  252. // MARK: Internal
  253. internal func updateConstantAndPriorityIfNeeded() {
  254. for layoutConstraint in self.layoutConstraints {
  255. let attribute = (layoutConstraint.secondAttribute == .notAnAttribute) ? layoutConstraint.firstAttribute : layoutConstraint.secondAttribute
  256. layoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: attribute)
  257. let requiredPriority = ConstraintPriority.required.value
  258. if (layoutConstraint.priority.rawValue < requiredPriority), (self.priority.constraintPriorityTargetValue != requiredPriority) {
  259. layoutConstraint.priority = LayoutPriority(rawValue: self.priority.constraintPriorityTargetValue)
  260. }
  261. }
  262. }
  263. internal func activateIfNeeded(updatingExisting: Bool = false) {
  264. guard let item = self.from.layoutConstraintItem else {
  265. print("WARNING: SnapKit failed to get from item from constraint. Activate will be a no-op.")
  266. return
  267. }
  268. let layoutConstraints = self.layoutConstraints
  269. if updatingExisting {
  270. var existingLayoutConstraints: [LayoutConstraint] = []
  271. for constraint in item.constraints {
  272. existingLayoutConstraints += constraint.layoutConstraints
  273. }
  274. for layoutConstraint in layoutConstraints {
  275. let existingLayoutConstraint = existingLayoutConstraints.first { $0 == layoutConstraint }
  276. guard let updateLayoutConstraint = existingLayoutConstraint else {
  277. fatalError("Updated constraint could not find existing matching constraint to update: \(layoutConstraint)")
  278. }
  279. let updateLayoutAttribute = (updateLayoutConstraint.secondAttribute == .notAnAttribute) ? updateLayoutConstraint.firstAttribute : updateLayoutConstraint.secondAttribute
  280. updateLayoutConstraint.constant = self.constant.constraintConstantTargetValueFor(layoutAttribute: updateLayoutAttribute)
  281. }
  282. } else {
  283. NSLayoutConstraint.activate(layoutConstraints)
  284. item.add(constraints: [self])
  285. }
  286. }
  287. internal func deactivateIfNeeded() {
  288. guard let item = self.from.layoutConstraintItem else {
  289. print("WARNING: SnapKit failed to get from item from constraint. Deactivate will be a no-op.")
  290. return
  291. }
  292. let layoutConstraints = self.layoutConstraints
  293. NSLayoutConstraint.deactivate(layoutConstraints)
  294. item.remove(constraints: [self])
  295. }
  296. }