LoginSignup
0
0

More than 1 year has passed since last update.

縦にページングするScrollViewを作成(UIScrollView)

Posted at

今回の内容

DA84C277-B012-4E55-BF91-DE1EDE28E6DC_1_201_a.jpeg 1B279A81-AF70-4323-92CB-FC622356FDD4_1_201_a.jpeg 0E8DE2AA-79E8-49F8-A579-F863B97B4B29_1_201_a.jpeg

コードと簡単解説

  • まずは、.isPagingEnabledtrueで設定して、ページングを可能にします。

  • .contentSizeでスクロールするサイズを設定します。今回は、縦にだけスクロールさせるので、widthview.frame.widthで設定します。

  • contentSizeheight: view.frame.height * 3を設定して、y軸方向に3段階のぺージングをする様にします。

import UIKit

class ViewController: UIViewController {

    let scrollView = UIScrollView()

    override func viewDidLoad() {
        super.viewDidLoad()

        scrollView.frame = CGRect(x: view.frame.minX, y: view.frame.minY, width: view.frame.width, height: view.frame.height)
        scrollView.contentSize = CGSize(width: view.frame.width, height: view.frame.height * 3)
        scrollView.isPagingEnabled = true
        scrollView.backgroundColor = .systemIndigo
        view.addSubview(scrollView)

        let topLabel = UILabel(frame: CGRect(x: scrollView.frame.maxX / 4, y: scrollView.frame.maxY / 10, width: scrollView.frame.width / 2, height: scrollView.frame.height / 20))
        topLabel.text = "Top"
        topLabel.font = UIFont.boldSystemFont(ofSize: 25)
        topLabel.textColor = .white
        topLabel.textAlignment = .center
        scrollView.addSubview(topLabel)

        let centerLabel = UILabel(frame: CGRect(x: scrollView.frame.maxX / 4, y: scrollView.frame.maxY + scrollView.frame.maxY / 10, width: scrollView.frame.width / 2, height: scrollView.frame.height / 20))
        centerLabel.text = "Center"
        centerLabel.font = UIFont.boldSystemFont(ofSize: 25)
        centerLabel.textColor = .white
        centerLabel.textAlignment = .center
        scrollView.addSubview(centerLabel)

        let bottomLabel = UILabel(frame: CGRect(x: scrollView.frame.maxX / 4, y: (scrollView.frame.maxY * 2) + scrollView.frame.maxY / 10, width: scrollView.frame.width / 2, height: scrollView.frame.height / 20))
        bottomLabel.text = "Bottom"
        bottomLabel.font = UIFont.boldSystemFont(ofSize: 25)
        bottomLabel.textColor = .white
        bottomLabel.textAlignment = .center
        scrollView.addSubview(bottomLabel)
    }

}

終わり

ご指摘、ご質問などありましたら、コメントまでお願い致します。

0
0
0

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
0
0