Constraint.swift 21 KB

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