0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

コードでUIScrollViewサンプル作成

Posted at

##バージョン

・Xcode12.4
・Swift5

##概要
コードでUIScrollViewのサンプルを作成した備忘録

##コード

test.swift
import UIKit

class ViewController: UIViewController {
// インスタンス化
    let outView = UIView()
    let scrollView = UIScrollView()
    let inView = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        // 背景色の決定
        scrollView.backgroundColor = UIColor.black
        inView.backgroundColor = UIColor.blue
        view.backgroundColor = UIColor.systemBlue
        
        // かくviewに子要素として追加
        scrollView.addSubview(inView)
        view.addSubview(scrollView)
        
        // scrollViewの制約の設定
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        scrollView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        scrollView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        
        // inViewの制約の設定
        // inView:AutoLayoutで使用したContainerViewに該当
        // Autosizingという仕組みをAutoLayoutに変換する設定するフラグ:falseでAutoLayoutを有効化
        inView.translatesAutoresizingMaskIntoConstraints = false

        // 横スクロールにするため、高さ:scrollViewと同一、幅:2000.0に設定
        inView.widthAnchor.constraint(equalToConstant: 2000.0).isActive = true
        inView.heightAnchor.constraint(equalTo: scrollView.heightAnchor).isActive = true
        inView.leftAnchor.constraint(equalTo: scrollView.leftAnchor).isActive = true
        inView.rightAnchor.constraint(equalTo: scrollView.rightAnchor).isActive = true
        inView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
        inView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
      }
    }

##参考にさせて頂いた記事
コードでUIScrollView(とその子どもたち)をAutoLayout配置
[Xcode11] UIScrollViewとAutolayoutのベストプラクティス

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?