Constraint.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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)
  24. import UIKit
  25. #else
  26. import AppKit
  27. #endif
  28. /**
  29. Used to expose API's for a Constraint
  30. */
  31. public class Constraint {
  32. public func install() -> [LayoutConstraint] { fatalError("Must be implemented by Concrete subclass.") }
  33. public func uninstall() -> Void { fatalError("Must be implemented by Concrete subclass.") }
  34. public func activate() -> Void { fatalError("Must be implemented by Concrete subclass.") }
  35. public func deactivate() -> Void { fatalError("Must be implemented by Concrete subclass.") }
  36. public func updateOffset(amount: Float) -> Void { fatalError("Must be implemented by Concrete subclass.") }
  37. public func updateOffset(amount: Double) -> Void { fatalError("Must be implemented by Concrete subclass.") }
  38. public func updateOffset(amount: CGFloat) -> Void { fatalError("Must be implemented by Concrete subclass.") }
  39. public func updateOffset(amount: Int) -> Void { fatalError("Must be implemented by Concrete subclass.") }
  40. public func updateOffset(amount: UInt) -> Void { fatalError("Must be implemented by Concrete subclass.") }
  41. public func updateOffset(amount: CGPoint) -> Void { fatalError("Must be implemented by Concrete subclass.") }
  42. public func updateOffset(amount: CGSize) -> Void { fatalError("Must be implemented by Concrete subclass.") }
  43. public func updateOffset(amount: EdgeInsets) -> Void { fatalError("Must be implemented by Concrete subclass.") }
  44. public func updateInsets(amount: EdgeInsets) -> Void { fatalError("Must be implemented by Concrete subclass.") }
  45. public func updatePriority(priority: Float) -> Void { fatalError("Must be implemented by Concrete subclass.") }
  46. public func updatePriority(priority: Double) -> Void { fatalError("Must be implemented by Concrete subclass.") }
  47. public func updatePriority(priority: CGFloat) -> Void { fatalError("Must be implemented by Concrete subclass.") }
  48. public func updatePriority(priority: UInt) -> Void { fatalError("Must be implemented by Concrete subclass.") }
  49. public func updatePriority(priority: Int) -> Void { fatalError("Must be implemented by Concrete subclass.") }
  50. public func updatePriorityRequired() -> Void { fatalError("Must be implemented by Concrete subclass.") }
  51. public func updatePriorityHigh() -> Void { fatalError("Must be implemented by Concrete subclass.") }
  52. public func updatePriorityMedium() -> Void { fatalError("Must be implemented by Concrete subclass.") }
  53. public func updatePriorityLow() -> Void { fatalError("Must be implemented by Concrete subclass.") }
  54. }
  55. /**
  56. Used internally to implement a ConcreteConstraint
  57. */
  58. internal class ConcreteConstraint: Constraint {
  59. internal override func updateOffset(amount: Float) -> Void {
  60. self.constant = amount
  61. }
  62. internal override func updateOffset(amount: Double) -> Void {
  63. self.updateOffset(Float(amount))
  64. }
  65. internal override func updateOffset(amount: CGFloat) -> Void {
  66. self.updateOffset(Float(amount))
  67. }
  68. internal override func updateOffset(amount: Int) -> Void {
  69. self.updateOffset(Float(amount))
  70. }
  71. internal override func updateOffset(amount: UInt) -> Void {
  72. self.updateOffset(Float(amount))
  73. }
  74. internal override func updateOffset(amount: CGPoint) -> Void {
  75. self.constant = amount
  76. }
  77. internal override func updateOffset(amount: CGSize) -> Void {
  78. self.constant = amount
  79. }
  80. internal override func updateOffset(amount: EdgeInsets) -> Void {
  81. self.constant = amount
  82. }
  83. internal override func updateInsets(amount: EdgeInsets) -> Void {
  84. self.constant = EdgeInsets(top: amount.top, left: amount.left, bottom: -amount.bottom, right: -amount.right)
  85. }
  86. internal override func updatePriority(priority: Float) -> Void {
  87. self.priority = priority
  88. }
  89. internal override func updatePriority(priority: Double) -> Void {
  90. self.updatePriority(Float(priority))
  91. }
  92. internal override func updatePriority(priority: CGFloat) -> Void {
  93. self.updatePriority(Float(priority))
  94. }
  95. internal override func updatePriority(priority: UInt) -> Void {
  96. self.updatePriority(Float(priority))
  97. }
  98. internal override func updatePriority(priority: Int) -> Void {
  99. self.updatePriority(Float(priority))
  100. }
  101. internal override func updatePriorityRequired() -> Void {
  102. self.updatePriority(Float(1000.0))
  103. }
  104. internal override func updatePriorityHigh() -> Void {
  105. self.updatePriority(Float(750.0))
  106. }
  107. internal override func updatePriorityMedium() -> Void {
  108. #if os(iOS)
  109. self.updatePriority(Float(500.0))
  110. #else
  111. self.updatePriority(Float(501.0))
  112. #endif
  113. }
  114. internal override func updatePriorityLow() -> Void {
  115. self.updatePriority(Float(250.0))
  116. }
  117. internal override func install() -> [LayoutConstraint] {
  118. return self.installOnView(updateExisting: false)
  119. }
  120. internal override func uninstall() -> Void {
  121. self.uninstallFromView()
  122. }
  123. internal override func activate() -> Void {
  124. if NSLayoutConstraint.respondsToSelector("activateConstraints:") && self.installInfo != nil {
  125. let layoutConstraints = self.installInfo!.layoutConstraints.allObjects as! [LayoutConstraint]
  126. if layoutConstraints.count > 0 {
  127. NSLayoutConstraint.activateConstraints(layoutConstraints)
  128. }
  129. } else {
  130. self.install()
  131. }
  132. }
  133. internal override func deactivate() -> Void {
  134. if NSLayoutConstraint.respondsToSelector("deactivateConstraints:") && self.installInfo != nil {
  135. let layoutConstraints = self.installInfo!.layoutConstraints.allObjects as! [LayoutConstraint]
  136. if layoutConstraints.count > 0 {
  137. NSLayoutConstraint.deactivateConstraints(layoutConstraints)
  138. }
  139. } else {
  140. self.uninstall()
  141. }
  142. }
  143. private let fromItem: ConstraintItem
  144. private let toItem: ConstraintItem
  145. private let relation: ConstraintRelation
  146. private let multiplier: Float
  147. private var constant: Any {
  148. didSet {
  149. if let installInfo = self.installInfo {
  150. for layoutConstraint in installInfo.layoutConstraints.allObjects as! [LayoutConstraint] {
  151. let attribute = (layoutConstraint.secondAttribute == .NotAnAttribute) ? layoutConstraint.firstAttribute : layoutConstraint.secondAttribute
  152. layoutConstraint.constant = attribute.snp_constantForValue(self.constant)
  153. }
  154. }
  155. }
  156. }
  157. private var priority: Float {
  158. didSet {
  159. if let installInfo = self.installInfo {
  160. for layoutConstraint in installInfo.layoutConstraints.allObjects as! [LayoutConstraint] {
  161. layoutConstraint.priority = self.priority
  162. }
  163. }
  164. }
  165. }
  166. private var installInfo: ConcreteConstraintInstallInfo? = nil
  167. internal init(fromItem: ConstraintItem, toItem: ConstraintItem, relation: ConstraintRelation, constant: Any, multiplier: Float, priority: Float) {
  168. self.fromItem = fromItem
  169. self.toItem = toItem
  170. self.relation = relation
  171. self.constant = constant
  172. self.multiplier = multiplier
  173. self.priority = priority
  174. }
  175. internal func installOnView(updateExisting: Bool = false) -> [LayoutConstraint] {
  176. var installOnView: View? = nil
  177. if self.toItem.view != nil {
  178. installOnView = closestCommonSuperviewBetween(self.fromItem.view, self.toItem.view)
  179. if installOnView == nil {
  180. NSException(name: "Cannot Install Constraint", reason: "No common superview between views", userInfo: nil).raise()
  181. return []
  182. }
  183. } else {
  184. installOnView = self.fromItem.view?.superview
  185. if installOnView == nil {
  186. if self.fromItem.attributes == ConstraintAttributes.Width || self.fromItem.attributes == ConstraintAttributes.Height {
  187. installOnView = self.fromItem.view
  188. }
  189. if installOnView == nil {
  190. NSException(name: "Cannot Install Constraint", reason: "Missing superview", userInfo: nil).raise()
  191. return []
  192. }
  193. }
  194. }
  195. if let installedOnView = self.installInfo?.view {
  196. if installedOnView != installOnView {
  197. NSException(name: "Cannot Install Constraint", reason: "Already installed on different view.", userInfo: nil).raise()
  198. return []
  199. }
  200. return self.installInfo?.layoutConstraints.allObjects as? [LayoutConstraint] ?? []
  201. }
  202. var newLayoutConstraints = [LayoutConstraint]()
  203. let layoutFromAttributes = self.fromItem.attributes.layoutAttributes
  204. let layoutToAttributes = self.toItem.attributes.layoutAttributes
  205. // get layout from
  206. let layoutFrom: View? = self.fromItem.view
  207. // get layout relation
  208. let layoutRelation: NSLayoutRelation = self.relation.layoutRelation
  209. for layoutFromAttribute in layoutFromAttributes {
  210. // get layout to attribute
  211. let layoutToAttribute = (layoutToAttributes.count > 0) ? layoutToAttributes[0] : layoutFromAttribute
  212. // get layout constant
  213. var layoutConstant: CGFloat = layoutToAttribute.snp_constantForValue(self.constant)
  214. // get layout to
  215. var layoutTo: View? = self.toItem.view
  216. if layoutTo == nil && layoutToAttribute != .Width && layoutToAttribute != .Height {
  217. layoutTo = installOnView
  218. }
  219. // create layout constraint
  220. let layoutConstraint = LayoutConstraint(
  221. item: layoutFrom!,
  222. attribute: layoutFromAttribute,
  223. relatedBy: layoutRelation,
  224. toItem: layoutTo,
  225. attribute: layoutToAttribute,
  226. multiplier: CGFloat(self.multiplier),
  227. constant: layoutConstant)
  228. // set priority
  229. layoutConstraint.priority = self.priority
  230. // set constraint
  231. layoutConstraint.snp_constraint = self
  232. newLayoutConstraints.append(layoutConstraint)
  233. }
  234. // special logic for updating
  235. if updateExisting {
  236. // get existing constraints for this view
  237. let existingLayoutConstraints = reverse(layoutFrom!.snp_installedLayoutConstraints)
  238. // array that will contain only new layout constraints to keep
  239. var newLayoutConstraintsToKeep = [LayoutConstraint]()
  240. // begin looping
  241. for layoutConstraint in newLayoutConstraints {
  242. // layout constraint that should be updated
  243. var updateLayoutConstraint: LayoutConstraint? = nil
  244. // loop through existing and check for match
  245. for existingLayoutConstraint in existingLayoutConstraints {
  246. if existingLayoutConstraint == layoutConstraint {
  247. updateLayoutConstraint = existingLayoutConstraint
  248. break
  249. }
  250. }
  251. // if we have existing one lets just update the constant
  252. if updateLayoutConstraint != nil {
  253. updateLayoutConstraint!.constant = layoutConstraint.constant
  254. }
  255. // otherwise add this layout constraint to new keep list
  256. else {
  257. newLayoutConstraintsToKeep.append(layoutConstraint)
  258. }
  259. }
  260. // set constraints to only new ones
  261. newLayoutConstraints = newLayoutConstraintsToKeep
  262. }
  263. // add constraints
  264. installOnView!.addConstraints(newLayoutConstraints)
  265. // set install info
  266. self.installInfo = ConcreteConstraintInstallInfo(view: installOnView, layoutConstraints: NSHashTable.weakObjectsHashTable())
  267. // store which layout constraints are installed for this constraint
  268. for layoutConstraint in newLayoutConstraints {
  269. self.installInfo!.layoutConstraints.addObject(layoutConstraint)
  270. }
  271. // store the layout constraints against the layout from view
  272. layoutFrom!.snp_installedLayoutConstraints += newLayoutConstraints
  273. // return the new constraints
  274. return newLayoutConstraints
  275. }
  276. internal func uninstallFromView() {
  277. if let installInfo = self.installInfo,
  278. let installedLayoutConstraints = installInfo.layoutConstraints.allObjects as? [LayoutConstraint] {
  279. if installedLayoutConstraints.count > 0 {
  280. if let installedOnView = installInfo.view {
  281. // remove the constraints from the UIView's storage
  282. installedOnView.removeConstraints(installedLayoutConstraints)
  283. }
  284. // remove the constraints from the from item view
  285. if let fromView = self.fromItem.view {
  286. fromView.snp_installedLayoutConstraints = fromView.snp_installedLayoutConstraints.filter {
  287. return !contains(installedLayoutConstraints, $0)
  288. }
  289. }
  290. }
  291. }
  292. self.installInfo = nil
  293. }
  294. }
  295. private struct ConcreteConstraintInstallInfo {
  296. weak var view: View? = nil
  297. let layoutConstraints: NSHashTable
  298. }
  299. private extension NSLayoutAttribute {
  300. private func snp_constantForValue(value: Any?) -> CGFloat {
  301. // Float
  302. if let float = value as? Float {
  303. return CGFloat(float)
  304. }
  305. // Double
  306. else if let double = value as? Double {
  307. return CGFloat(double)
  308. }
  309. // UInt
  310. else if let int = value as? Int {
  311. return CGFloat(int)
  312. }
  313. // Int
  314. else if let uint = value as? UInt {
  315. return CGFloat(uint)
  316. }
  317. // CGFloat
  318. else if let float = value as? CGFloat {
  319. return float
  320. }
  321. // CGSize
  322. else if let size = value as? CGSize {
  323. if self == .Width {
  324. return size.width
  325. } else if self == .Height {
  326. return size.height
  327. }
  328. }
  329. // CGPoint
  330. else if let point = value as? CGPoint {
  331. #if os(iOS)
  332. switch self {
  333. case .Left, .CenterX, .LeftMargin, .CenterXWithinMargins: return point.x
  334. case .Top, .CenterY, .TopMargin, .CenterYWithinMargins, .Baseline, .FirstBaseline: return point.y
  335. case .Right, .RightMargin: return point.x
  336. case .Bottom, .BottomMargin: return point.y
  337. case .Leading, .LeadingMargin: return point.x
  338. case .Trailing, .TrailingMargin: return point.x
  339. case .Width, .Height, .NotAnAttribute: return CGFloat(0)
  340. }
  341. #else
  342. switch self {
  343. case .Left, .CenterX: return point.x
  344. case .Top, .CenterY, .Baseline: return point.y
  345. case .Right: return point.x
  346. case .Bottom: return point.y
  347. case .Leading: return point.x
  348. case .Trailing: return point.x
  349. case .Width, .Height, .NotAnAttribute: return CGFloat(0)
  350. }
  351. #endif
  352. }
  353. // EdgeInsets
  354. else if let insets = value as? EdgeInsets {
  355. #if os(iOS)
  356. switch self {
  357. case .Left, .CenterX, .LeftMargin, .CenterXWithinMargins: return insets.left
  358. case .Top, .CenterY, .TopMargin, .CenterYWithinMargins, .Baseline, .FirstBaseline: return insets.top
  359. case .Right, .RightMargin: return insets.right
  360. case .Bottom, .BottomMargin: return insets.bottom
  361. case .Leading, .LeadingMargin: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.left : -insets.right
  362. case .Trailing, .TrailingMargin: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.right : -insets.left
  363. case .Width, .Height, .NotAnAttribute: return CGFloat(0)
  364. }
  365. #else
  366. switch self {
  367. case .Left, .CenterX: return insets.left
  368. case .Top, .CenterY, .Baseline: return insets.top
  369. case .Right: return insets.right
  370. case .Bottom: return insets.bottom
  371. case .Leading: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.left : -insets.right
  372. case .Trailing: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.right : -insets.left
  373. case .Width, .Height, .NotAnAttribute: return CGFloat(0)
  374. }
  375. #endif
  376. }
  377. return CGFloat(0);
  378. }
  379. }
  380. private func closestCommonSuperviewBetween(fromView: View?, toView: View?) -> View? {
  381. var views = Set<View>()
  382. var fromView = fromView
  383. var toView = toView
  384. do {
  385. if let view = toView {
  386. if views.contains(view) {
  387. return view
  388. }
  389. views.insert(view)
  390. toView = view.superview
  391. }
  392. if let view = fromView {
  393. if views.contains(view) {
  394. return view
  395. }
  396. views.insert(view)
  397. fromView = view.superview
  398. }
  399. } while (fromView != nil || toView != nil)
  400. return nil
  401. }
  402. private func ==(left: ConcreteConstraint, right: ConcreteConstraint) -> Bool {
  403. return (left.fromItem == right.fromItem &&
  404. left.toItem == right.toItem &&
  405. left.relation == right.relation &&
  406. left.multiplier == right.multiplier &&
  407. left.priority == right.priority)
  408. }