Skip to content

Instantly share code, notes, and snippets.

@freddi-kit
Last active August 12, 2018 06:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save freddi-kit/f886ef73d8fe523ebffcffd8f3f68726 to your computer and use it in GitHub Desktop.
Save freddi-kit/f886ef73d8fe523ebffcffd8f3f68726 to your computer and use it in GitHub Desktop.
Scroll Viewのページングでのページ追加を簡単にできるようにした ref: https://qiita.com/freddi_/items/63e2592c8a18794650a8
// ViewController内
// 1. ページ数
let pageCount = 2
// 3. StackViewの作成
let contentView = UIStackView()
// 2. 紐づけたScroll View
@IBOutlet weak var scrollView: UIScrollView! {
didSet {
// 2. ページングをON
scrollView.isPagingEnabled = true
}
}
func viewDidLoad() {
...
// 3.
// 以下のようにすると横向きのページングとして使用することができ、追加されたページのレイアウトもStack Viewが揃えてくれる
// 以下のプロパティの説明は、https://qiita.com/tasanobu/items/6908c956b758547ccf6c を参照
contentView.spacing = 0.0
contentView.axis = .horizontal
contentView.alignment = .fill
contentView.distribution = .fillEqually
scrollView.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
// 先程のソースのviewDidLoad内での続き
// かなり重要
NSLayoutConstraint.activate([
// Top Bottom Leading TrailingはすべてScroll Viewに合わせる
contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
// HeightはscrollViewに合わせる。
contentView.heightAnchor.constraint(equalTo: scrollView.heightAnchor),
// WidthはscrollView.widthAnchor x ページ数
contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor, multiplier: CGFloat(pagesCounts))
])
// viewDidLoadでの続き
let redView = UIView()
redView.backgroundColor = .red
// Stack Viewへの追加なのでaddArrangedSubview
contentView.addArrangedSubview(redView)
let blueView = UIView()
blueView.backgroundColor = .blue
contentView.addArrangedSubview(blueView)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment