Constraint.swift 19 KB

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