Constraint.swift 21 KB

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