Constraint.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  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 let label: String?
  179. private var installInfo: ConcreteConstraintInstallInfo? = nil
  180. internal init(fromItem: ConstraintItem, toItem: ConstraintItem, relation: ConstraintRelation, constant: Any, multiplier: Float, priority: Float, label: String? = nil) {
  181. self.fromItem = fromItem
  182. self.toItem = toItem
  183. self.relation = relation
  184. self.constant = constant
  185. self.multiplier = multiplier
  186. self.priority = priority
  187. self.label = label
  188. }
  189. internal func installOnView(updateExisting updateExisting: Bool = false, file: String? = nil, line: UInt? = nil) -> [LayoutConstraint] {
  190. var installOnView: View? = nil
  191. if self.toItem.view != nil {
  192. installOnView = closestCommonSuperviewFromView(self.fromItem.view, toView: self.toItem.view)
  193. if installOnView == nil {
  194. NSException(name: "Cannot Install Constraint", reason: "No common superview between views (@\(self.makerFile)#\(self.makerLine))", userInfo: nil).raise()
  195. return []
  196. }
  197. } else {
  198. if self.fromItem.attributes.isSubsetOf(ConstraintAttributes.Width.union(.Height)) {
  199. installOnView = self.fromItem.view
  200. } else {
  201. installOnView = self.fromItem.view?.superview
  202. if installOnView == nil {
  203. NSException(name: "Cannot Install Constraint", reason: "Missing superview (@\(self.makerFile)#\(self.makerLine))", userInfo: nil).raise()
  204. return []
  205. }
  206. }
  207. }
  208. if let installedOnView = self.installInfo?.view {
  209. if installedOnView != installOnView {
  210. NSException(name: "Cannot Install Constraint", reason: "Already installed on different view. (@\(self.makerFile)#\(self.makerLine))", userInfo: nil).raise()
  211. return []
  212. }
  213. return self.installInfo?.layoutConstraints.allObjects as? [LayoutConstraint] ?? []
  214. }
  215. var newLayoutConstraints = [LayoutConstraint]()
  216. let layoutFromAttributes = self.fromItem.attributes.layoutAttributes
  217. let layoutToAttributes = self.toItem.attributes.layoutAttributes
  218. // get layout from
  219. let layoutFrom: View? = self.fromItem.view
  220. // get layout relation
  221. let layoutRelation: NSLayoutRelation = self.relation.layoutRelation
  222. for layoutFromAttribute in layoutFromAttributes {
  223. // get layout to attribute
  224. let layoutToAttribute = (layoutToAttributes.count > 0) ? layoutToAttributes[0] : layoutFromAttribute
  225. // get layout constant
  226. let layoutConstant: CGFloat = layoutToAttribute.snp_constantForValue(self.constant)
  227. // get layout to
  228. #if os(iOS) || os(tvOS)
  229. var layoutTo: AnyObject? = self.toItem.view ?? self.toItem.layoutSupport
  230. #else
  231. var layoutTo: AnyObject? = self.toItem.view
  232. #endif
  233. if layoutTo == nil && layoutToAttribute != .Width && layoutToAttribute != .Height {
  234. layoutTo = installOnView
  235. }
  236. // create layout constraint
  237. let layoutConstraint = LayoutConstraint(
  238. item: layoutFrom!,
  239. attribute: layoutFromAttribute,
  240. relatedBy: layoutRelation,
  241. toItem: layoutTo,
  242. attribute: layoutToAttribute,
  243. multiplier: CGFloat(self.multiplier),
  244. constant: layoutConstant)
  245. layoutConstraint.identifier = self.label
  246. // set priority
  247. layoutConstraint.priority = self.priority
  248. // set constraint
  249. layoutConstraint.snp_constraint = self
  250. newLayoutConstraints.append(layoutConstraint)
  251. }
  252. // special logic for updating
  253. if updateExisting {
  254. // get existing constraints for this view
  255. let existingLayoutConstraints = layoutFrom!.snp_installedLayoutConstraints.reverse()
  256. // array that will contain only new layout constraints to keep
  257. var newLayoutConstraintsToKeep = [LayoutConstraint]()
  258. // begin looping
  259. for layoutConstraint in newLayoutConstraints {
  260. // layout constraint that should be updated
  261. var updateLayoutConstraint: LayoutConstraint? = nil
  262. // loop through existing and check for match
  263. for existingLayoutConstraint in existingLayoutConstraints {
  264. if existingLayoutConstraint == layoutConstraint {
  265. updateLayoutConstraint = existingLayoutConstraint
  266. break
  267. }
  268. }
  269. // if we have existing one lets just update the constant
  270. if updateLayoutConstraint != nil {
  271. updateLayoutConstraint!.constant = layoutConstraint.constant
  272. }
  273. // otherwise add this layout constraint to new keep list
  274. else {
  275. newLayoutConstraintsToKeep.append(layoutConstraint)
  276. }
  277. }
  278. // set constraints to only new ones
  279. newLayoutConstraints = newLayoutConstraintsToKeep
  280. }
  281. // add constraints
  282. #if SNAPKIT_DEPLOYMENT_LEGACY && !os(OSX)
  283. if #available(iOS 8.0, *) {
  284. NSLayoutConstraint.activateConstraints(newLayoutConstraints)
  285. } else {
  286. installOnView!.addConstraints(newLayoutConstraints)
  287. }
  288. #else
  289. NSLayoutConstraint.activateConstraints(newLayoutConstraints)
  290. #endif
  291. // set install info
  292. self.installInfo = ConcreteConstraintInstallInfo(view: installOnView, layoutConstraints: NSHashTable.weakObjectsHashTable())
  293. // store which layout constraints are installed for this constraint
  294. for layoutConstraint in newLayoutConstraints {
  295. self.installInfo!.layoutConstraints.addObject(layoutConstraint)
  296. }
  297. // store the layout constraints against the layout from view
  298. layoutFrom!.snp_installedLayoutConstraints += newLayoutConstraints
  299. // return the new constraints
  300. return newLayoutConstraints
  301. }
  302. internal func uninstallFromView() {
  303. if let installInfo = self.installInfo,
  304. let installedLayoutConstraints = installInfo.layoutConstraints.allObjects as? [LayoutConstraint] {
  305. if installedLayoutConstraints.count > 0 {
  306. // remove the constraints from the UIView's storage
  307. #if SNAPKIT_DEPLOYMENT_LEGACY && !os(OSX)
  308. if #available(iOS 8.0, *) {
  309. NSLayoutConstraint.deactivateConstraints(installedLayoutConstraints)
  310. } else if let installedOnView = installInfo.view {
  311. installedOnView.removeConstraints(installedLayoutConstraints)
  312. }
  313. #else
  314. NSLayoutConstraint.deactivateConstraints(installedLayoutConstraints)
  315. #endif
  316. // remove the constraints from the from item view
  317. if let fromView = self.fromItem.view {
  318. fromView.snp_installedLayoutConstraints = fromView.snp_installedLayoutConstraints.filter {
  319. return !installedLayoutConstraints.contains($0)
  320. }
  321. }
  322. }
  323. }
  324. self.installInfo = nil
  325. }
  326. }
  327. private struct ConcreteConstraintInstallInfo {
  328. weak var view: View? = nil
  329. let layoutConstraints: NSHashTable
  330. }
  331. private extension NSLayoutAttribute {
  332. private func snp_constantForValue(value: Any?) -> CGFloat {
  333. // Float
  334. if let float = value as? Float {
  335. return CGFloat(float)
  336. }
  337. // Double
  338. else if let double = value as? Double {
  339. return CGFloat(double)
  340. }
  341. // UInt
  342. else if let int = value as? Int {
  343. return CGFloat(int)
  344. }
  345. // Int
  346. else if let uint = value as? UInt {
  347. return CGFloat(uint)
  348. }
  349. // CGFloat
  350. else if let float = value as? CGFloat {
  351. return float
  352. }
  353. // CGSize
  354. else if let size = value as? CGSize {
  355. if self == .Width {
  356. return size.width
  357. } else if self == .Height {
  358. return size.height
  359. }
  360. }
  361. // CGPoint
  362. else if let point = value as? CGPoint {
  363. #if os(iOS) || os(tvOS)
  364. switch self {
  365. case .Left, .CenterX, .LeftMargin, .CenterXWithinMargins: return point.x
  366. case .Top, .CenterY, .TopMargin, .CenterYWithinMargins, .LastBaseline, .FirstBaseline: return point.y
  367. case .Right, .RightMargin: return point.x
  368. case .Bottom, .BottomMargin: return point.y
  369. case .Leading, .LeadingMargin: return point.x
  370. case .Trailing, .TrailingMargin: return point.x
  371. case .Width, .Height, .NotAnAttribute: return CGFloat(0)
  372. }
  373. #else
  374. switch self {
  375. case .Left, .CenterX: return point.x
  376. case .Top, .CenterY, .LastBaseline: return point.y
  377. case .Right: return point.x
  378. case .Bottom: return point.y
  379. case .Leading: return point.x
  380. case .Trailing: return point.x
  381. case .Width, .Height, .NotAnAttribute: return CGFloat(0)
  382. case .FirstBaseline: return point.y
  383. }
  384. #endif
  385. }
  386. // EdgeInsets
  387. else if let insets = value as? EdgeInsets {
  388. #if os(iOS) || os(tvOS)
  389. switch self {
  390. case .Left, .CenterX, .LeftMargin, .CenterXWithinMargins: return insets.left
  391. case .Top, .CenterY, .TopMargin, .CenterYWithinMargins, .LastBaseline, .FirstBaseline: return insets.top
  392. case .Right, .RightMargin: return insets.right
  393. case .Bottom, .BottomMargin: return insets.bottom
  394. case .Leading, .LeadingMargin: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.left : -insets.right
  395. case .Trailing, .TrailingMargin: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.right : -insets.left
  396. case .Width: return -insets.left + insets.right
  397. case .Height: return -insets.top + insets.bottom
  398. case .NotAnAttribute: return CGFloat(0)
  399. }
  400. #else
  401. switch self {
  402. case .Left, .CenterX: return insets.left
  403. case .Top, .CenterY, .LastBaseline: return insets.top
  404. case .Right: return insets.right
  405. case .Bottom: return insets.bottom
  406. case .Leading: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.left : -insets.right
  407. case .Trailing: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.right : -insets.left
  408. case .Width: return -insets.left + insets.right
  409. case .Height: return -insets.top + insets.bottom
  410. case .NotAnAttribute: return CGFloat(0)
  411. case .FirstBaseline: return insets.bottom
  412. }
  413. #endif
  414. }
  415. return CGFloat(0);
  416. }
  417. }
  418. private func closestCommonSuperviewFromView(fromView: View?, toView: View?) -> View? {
  419. var views = Set<View>()
  420. var fromView = fromView
  421. var toView = toView
  422. repeat {
  423. if let view = toView {
  424. if views.contains(view) {
  425. return view
  426. }
  427. views.insert(view)
  428. toView = view.superview
  429. }
  430. if let view = fromView {
  431. if views.contains(view) {
  432. return view
  433. }
  434. views.insert(view)
  435. fromView = view.superview
  436. }
  437. } while (fromView != nil || toView != nil)
  438. return nil
  439. }
  440. private func ==(left: ConcreteConstraint, right: ConcreteConstraint) -> Bool {
  441. return (left.fromItem == right.fromItem &&
  442. left.toItem == right.toItem &&
  443. left.relation == right.relation &&
  444. left.multiplier == right.multiplier &&
  445. left.priority == right.priority)
  446. }