LoginSignup
14
19

More than 5 years have passed since last update.

Swift 3のUIScrollViewでカルーセルUI(ページング/画像などをスワイプで行き来できるView)をつくる

Last updated at Posted at 2017-03-01

カルーセルUIを実装しようとしてUICollectionViewでやろうとしたりiCarouselがいいかなーと悩んだりしたのですが、UIScrollViewを用いた方法がとても平易で分かりやすかったのでSwift 3版載せさせていただきます。

出典はこちら↓

[XCODE] UIScrollViewを用いてページングUIを実現する方法 / YoheiM.NET
http://www.yoheim.net/blog.php?q=20120715

Storyboard

螢幕快照_2017-03-01_11_52_08.png

必ず Paging Enabled にチェック を入れます。

Code

ViewController.swift
let size = CGSize(width: scrollView.frame.size.width, height: 200)

let contentRect = CGRect(x: 0, y: 0, width: size.width * 4, height: size.height)
let contentView = UIView(frame: contentRect)

let subContentView = UIView(frame: CGRect(x: 0, y: 0, width: size.width, height: size.height))
subContentView.backgroundColor = .green
contentView.addSubview(subContentView)

let secondContentView = UIView(frame: CGRect(x: size.width, y: 0, width: size.width, height: size.height))
secondContentView.backgroundColor = .blue
contentView.addSubview(secondContentView)

let thirdContentView = UIView(frame: CGRect(x: size.width * 2, y: 0, width: size.width, height: size.height))
thirdContentView.backgroundColor = .red
contentView.addSubview(thirdContentView)

let fourthContentView = UIView(frame: CGRect(x: size.width * 3, y: 0, width: size.width, height: size.height))
fourthContentView.backgroundColor = .yellow
contentView.addSubview(fourthContentView)

scrollView.addSubview(contentView)
scrollView.contentSize = contentView.frame.size
scrollView.contentOffset = CGPoint(x: size.width, y: 0)

Result

hoge.gif

:sunglasses::thumbsup: DEAL WITH IT!

コード置いときます。

https://github.com/keisei1092/CarouselByUIScrollViewPractice

14
19
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
19