Constraint.swift 20 KB

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