SwiftでSnapChatっぽいUI

SwiftでSnapChatぽいUI、左右のスワイプでViewControllerが切り替わるやつをやってみた。

f:id:aminaura:20160503073406j:plain

まずは大元となるContainerViewControllerを作って(Containerという名前が正しいかはわからないけど)、その上に敷いたScrollViewにVCたちをaddChildViewControllerしていく感じ。

class ContainerViewController: UIViewController {

    private var offset = 0
    private var viewControllers = [UIViewController]()

    internal init(controllers: [UIViewController], offset: Int) {
        super.init(nibName: nil, bundle: nil)
        controllers.forEach { viewControllers.append($0) }
        self.offset = offset
    }

    private func setupScrollView() {
        let viewBounds = self.view.bounds
        let viewWidth = viewBounds.width

        let scrollView = UIScrollView()
        scrollView.delegate = self
        scrollView.pagingEnabled = true
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
        scrollView.frame = CGRect(x: viewBounds.origin.x, y: viewBounds.origin.y, width: viewWidth, height: CGRectGetHeight(viewBounds))

        self.view.addSubview(scrollView)
        scrollView.contentSize = CGSize(width: CGFloat(viewControllers.count) * viewWidth, height: CGRectGetHeight(viewBounds))

        for (index, vc) in viewControllers.enumerate() {
            vc.view.frame = CGRect(x: CGFloat(index)*viewWidth, y: 0, width: viewWidth, height: CGRectGetHeight(viewBounds))
            self.addChildViewController(vc)
            scrollView.addSubview(vc.view)
            vc.didMoveToParentViewController(self)
            scrollView.sendSubviewToBack(vc.view)
        }
        scrollView.contentOffset.x = viewControllers[offset].view.frame.origin.x
    }
}

ContainerViewControllerの初期化はアプリ起動時にこんな感じで行ってる。

internal func setup(application: UIApplication) {
        let cameraSB = UIStoryboard(name: "Camera", bundle: nil)
        let feedSB = UIStoryboard(name: "Feed", bundle: nil)
        let profileSB = UIStoryboard(name: "Profile", bundle: nil)

        let camera = cameraSB.instantiateViewControllerWithIdentifier("camera")
        let feed = feedSB.instantiateViewControllerWithIdentifier("feed")
        let profile = profileSB.instantiateViewControllerWithIdentifier("profile")
        let controllers = [feed, camera, profile]

        let container = ContainerViewController(controllers: controllers, offset: 1)
        self.window?.rootViewController = container
        self.window?.makeKeyAndVisible()
    }

(実際のコードから削っているのでそのままだと動かないかもしれないです)