カテゴリー
iOS Swift

UIScrollViewの設定

UIScrollViewをスクロールさせるためには、scrollViewにSubviewとしてもう一つUIViewをcontentsViewとして追加し、contentsView.frame.sizeをscrollView.contentSizeに教える必要があります。

import UIKit

class ViewController: UIViewController {

  // MARK: - UI Components
	
  lazy var scrollView: UIScrollView = {
    let scrollView = UIScrollView()
    return scrollView
  }()
	
  lazy var contentsView: UIView = {
    let contentsView = UIView()
    return contentsView
  }()
	
  var labels: [UILabel] = []
	
  // MARK: - Lifecycle
  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .blue
    addViews()
  }
	
  override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    setupLayouts()
  }
	
  private func addViews() {
    view.addSubview(scrollView)
    scrollView.addSubview(contentsView)
  }
	
  // MARK: - Layouts
  private func setupLayouts() {
    // remove and clear labels
    labels.forEach { label in
      label.removeFromSuperview()
    }
    labels = []
		
    // constraining scrollView to the view
    scrollView.frame = CGRect(x: 0, y: 0, width: view.bounds.width/2, height: view.bounds.height/2)
    scrollView.backgroundColor = .white
		
    // to only allow vertical scroll, constrain the contentsView width to the scrollView width
    contentsView.frame = CGRect(x: 0, y: 0, width: scrollView.bounds.width, height: 0)
		
    // to get aprox. same fontSize when the screen rotates
    var fontSize: CGFloat = 0
    if view.bounds.width > view.bounds.height {
      fontSize = view.bounds.height*0.5*0.2
    } else {
      fontSize = view.bounds.width*0.5*0.2
    }
		
    // adding labels to the contentsView
    for i in 0..<50 {
      let label = UILabel()
      label.frame = CGRect(x: 0, y: CGFloat(i)*fontSize, width: contentsView.bounds.width, height: fontSize)
      label.font = UIFont(name: "HelveticaNeue-CondensedBold", size: fontSize)
      label.text = "Label \(i)"
      label.textColor = .black
      contentsView.addSubview(label)
      // retaining lables for removing from its superView for when screen rotates, etc...
      labels.append(label)
    }
		
    // adjusting the contentsView height to the number of lables added
    contentsView.frame.size = CGSize(width: scrollView.bounds.width, height: fontSize*50)
		
    // to tell the scrollView the frame.size of the contentsView is important, otherwise will not scroll
    scrollView.contentSize = contentsView.frame.size
  }
}