Constraint.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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 makerLocation: SourceLocation = SourceLocation(file: "Unknown", line: 0)
  55. internal(set) public var location: SourceLocation?
  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, location: self.makerLocation)
  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, location: SourceLocation?) {
  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. super.init()
  187. self.location = location
  188. }
  189. internal func installOnView(updateExisting updateExisting: Bool = false, location: SourceLocation? = 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.makerLocation.file)#\(self.makerLocation.line))", 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.makerLocation.file)#\(self.self.makerLocation.line))", 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.makerLocation.file)#\(self.makerLocation.line))", 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. // set priority
  246. layoutConstraint.priority = self.priority
  247. // set constraint
  248. layoutConstraint.snp_constraint = self
  249. newLayoutConstraints.append(layoutConstraint)
  250. }
  251. // special logic for updating
  252. if updateExisting {
  253. // get existing constraints for this view
  254. let existingLayoutConstraints = layoutFrom!.snp_installedLayoutConstraints.reverse()
  255. // array that will contain only new layout constraints to keep
  256. var newLayoutConstraintsToKeep = [LayoutConstraint]()
  257. // begin looping
  258. for layoutConstraint in newLayoutConstraints {
  259. // layout constraint that should be updated
  260. var updateLayoutConstraint: LayoutConstraint? = nil
  261. // loop through existing and check for match
  262. for existingLayoutConstraint in existingLayoutConstraints {
  263. if existingLayoutConstraint == layoutConstraint {
  264. updateLayoutConstraint = existingLayoutConstraint
  265. break
  266. }
  267. }
  268. // if we have existing one lets just update the constant
  269. if updateLayoutConstraint != nil {
  270. updateLayoutConstraint!.constant = layoutConstraint.constant
  271. }
  272. // otherwise add this layout constraint to new keep list
  273. else {
  274. newLayoutConstraintsToKeep.append(layoutConstraint)
  275. }
  276. }
  277. // set constraints to only new ones
  278. newLayoutConstraints = newLayoutConstraintsToKeep
  279. }
  280. // add constraints
  281. #if SNAPKIT_DEPLOYMENT_LEGACY && !os(OSX)
  282. if #available(iOS 8.0, *) {
  283. NSLayoutConstraint.activateConstraints(newLayoutConstraints)
  284. } else {
  285. installOnView!.addConstraints(newLayoutConstraints)
  286. }
  287. #else
  288. NSLayoutConstraint.activateConstraints(newLayoutConstraints)
  289. #endif
  290. // set install info
  291. self.installInfo = ConcreteConstraintInstallInfo(view: installOnView, layoutConstraints: NSHashTable.weakObjectsHashTable())
  292. // store which layout constraints are installed for this constraint
  293. for layoutConstraint in newLayoutConstraints {
  294. self.installInfo!.layoutConstraints.addObject(layoutConstraint)
  295. }
  296. // store the layout constraints against the layout from view
  297. layoutFrom!.snp_installedLayoutConstraints += newLayoutConstraints
  298. // return the new constraints
  299. return newLayoutConstraints
  300. }
  301. internal func uninstallFromView() {
  302. if let installInfo = self.installInfo,
  303. let installedLayoutConstraints = installInfo.layoutConstraints.allObjects as? [LayoutConstraint] {
  304. if installedLayoutConstraints.count > 0 {
  305. // remove the constraints from the UIView's storage
  306. #if SNAPKIT_DEPLOYMENT_LEGACY && !os(OSX)
  307. if #available(iOS 8.0, *) {
  308. NSLayoutConstraint.deactivateConstraints(installedLayoutConstraints)
  309. } else if let installedOnView = installInfo.view {
  310. installedOnView.removeConstraints(installedLayoutConstraints)
  311. }
  312. #else
  313. NSLayoutConstraint.deactivateConstraints(installedLayoutConstraints)
  314. #endif
  315. // remove the constraints from the from item view
  316. if let fromView = self.fromItem.view {
  317. fromView.snp_installedLayoutConstraints = fromView.snp_installedLayoutConstraints.filter {
  318. return !installedLayoutConstraints.contains($0)
  319. }
  320. }
  321. }
  322. }
  323. self.installInfo = nil
  324. }
  325. }
  326. private struct ConcreteConstraintInstallInfo {
  327. weak var view: View? = nil
  328. let layoutConstraints: NSHashTable
  329. }
  330. private extension NSLayoutAttribute {
  331. private func snp_constantForValue(value: Any?) -> CGFloat {
  332. // Float
  333. if let float = value as? Float {
  334. return CGFloat(float)
  335. }
  336. // Double
  337. else if let double = value as? Double {
  338. return CGFloat(double)
  339. }
  340. // UInt
  341. else if let int = value as? Int {
  342. return CGFloat(int)
  343. }
  344. // Int
  345. else if let uint = value as? UInt {
  346. return CGFloat(uint)
  347. }
  348. // CGFloat
  349. else if let float = value as? CGFloat {
  350. return float
  351. }
  352. // CGSize
  353. else if let size = value as? CGSize {
  354. if self == .Width {
  355. return size.width
  356. } else if self == .Height {
  357. return size.height
  358. }
  359. }
  360. // CGPoint
  361. else if let point = value as? CGPoint {
  362. #if os(iOS) || os(tvOS)
  363. switch self {
  364. case .Left, .CenterX, .LeftMargin, .CenterXWithinMargins: return point.x
  365. case .Top, .CenterY, .TopMargin, .CenterYWithinMargins, .Baseline, .FirstBaseline: return point.y
  366. case .Right, .RightMargin: return point.x
  367. case .Bottom, .BottomMargin: return point.y
  368. case .Leading, .LeadingMargin: return point.x
  369. case .Trailing, .TrailingMargin: return point.x
  370. case .Width, .Height, .NotAnAttribute: return CGFloat(0)
  371. }
  372. #else
  373. switch self {
  374. case .Left, .CenterX: return point.x
  375. case .Top, .CenterY, .Baseline: return point.y
  376. case .Right: return point.x
  377. case .Bottom: return point.y
  378. case .Leading: return point.x
  379. case .Trailing: return point.x
  380. case .Width, .Height, .NotAnAttribute: return CGFloat(0)
  381. case .FirstBaseline: return point.y
  382. }
  383. #endif
  384. }
  385. // EdgeInsets
  386. else if let insets = value as? EdgeInsets {
  387. #if os(iOS) || os(tvOS)
  388. switch self {
  389. case .Left, .CenterX, .LeftMargin, .CenterXWithinMargins: return insets.left
  390. case .Top, .CenterY, .TopMargin, .CenterYWithinMargins, .Baseline, .FirstBaseline: return insets.top
  391. case .Right, .RightMargin: return insets.right
  392. case .Bottom, .BottomMargin: return insets.bottom
  393. case .Leading, .LeadingMargin: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.left : -insets.right
  394. case .Trailing, .TrailingMargin: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.right : -insets.left
  395. case .Width: return -insets.left + insets.right
  396. case .Height: return -insets.top + insets.bottom
  397. case .NotAnAttribute: return CGFloat(0)
  398. }
  399. #else
  400. switch self {
  401. case .Left, .CenterX: return insets.left
  402. case .Top, .CenterY, .Baseline: return insets.top
  403. case .Right: return insets.right
  404. case .Bottom: return insets.bottom
  405. case .Leading: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.left : -insets.right
  406. case .Trailing: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.right : -insets.left
  407. case .Width: return -insets.left + insets.right
  408. case .Height: return -insets.top + insets.bottom
  409. case .NotAnAttribute: return CGFloat(0)
  410. case .FirstBaseline: return insets.bottom
  411. }
  412. #endif
  413. }
  414. return CGFloat(0);
  415. }
  416. }
  417. private func closestCommonSuperviewFromView(fromView: View?, toView: View?) -> View? {
  418. var views = Set<View>()
  419. var fromView = fromView
  420. var toView = toView
  421. repeat {
  422. if let view = toView {
  423. if views.contains(view) {
  424. return view
  425. }
  426. views.insert(view)
  427. toView = view.superview
  428. }
  429. if let view = fromView {
  430. if views.contains(view) {
  431. return view
  432. }
  433. views.insert(view)
  434. fromView = view.superview
  435. }
  436. } while (fromView != nil || toView != nil)
  437. return nil
  438. }
  439. private func ==(left: ConcreteConstraint, right: ConcreteConstraint) -> Bool {
  440. return (left.fromItem == right.fromItem &&
  441. left.toItem == right.toItem &&
  442. left.relation == right.relation &&
  443. left.multiplier == right.multiplier &&
  444. left.priority == right.priority)
  445. }