Created
July 26, 2016 21:47
-
-
Save IanKeen/84819689f8850ebf32b9de0102df34cd to your computer and use it in GitHub Desktop.
UIView.move(_:to) concept - a thought about a what a 'swifty' api might look like
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public enum ViewIndex { | |
case front, back | |
case index(Int) | |
case above(UIView) | |
case below(UIView) | |
} | |
private extension ViewIndex { | |
private func indexOfView(view: UIView, in parent: UIView) throws -> Int { | |
guard let index = parent.subviews.index(of: view) else { throw ViewIndexError.viewNotInHierarchy(view) } | |
return index | |
} | |
func indexIn(parent: UIView) throws -> Int { | |
switch self { | |
case .back: return 0 | |
case .front: return parent.subviews.count | |
case .index(let value): return value | |
case .above(let target): return try self.indexOfView(view: target, in: parent).advanced(by: 1) | |
case .below(let target): return try self.indexOfView(view: target, in: parent).advanced(by: -1) | |
} | |
} | |
} | |
public enum ViewIndexError: Error { | |
case viewNotInHierarchy(UIView) | |
} | |
public extension UIView { | |
public func move(_ view: UIView, to index: ViewIndex) throws { | |
view.removeFromSuperview() | |
self.insertSubview(view, at: try index.indexIn(parent: self)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment