Last active
August 12, 2018 06:15
-
-
Save freddi-kit/f886ef73d8fe523ebffcffd8f3f68726 to your computer and use it in GitHub Desktop.
Scroll Viewのページングでのページ追加を簡単にできるようにした ref: https://qiita.com/freddi_/items/63e2592c8a18794650a8
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
// 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 | |
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
// 先程のソースの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)) | |
]) |
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
// 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