LoginSignup
3
6

More than 5 years have passed since last update.

iOSでAndroidのFragmentのような実装をする (iOSで画面入れ替え)

Posted at

はじめに

iOSでAndroidのFragmentのような実装をしたいと考えました。
AndroidのFragmentのような…というのは、ここでは1画面の中に固定View(Activity)と複数可変View(Fragment)があり、可変Viewがそれぞれ入れ替わるようなイメージしています。
image.jpeg

実現方法

今回は、ボタンを押したら2つのViewが切り替わるサンプルをつくりました。

storyboard

image.png
このような構造にしました。薄い青いViewがContainerです。

ViewController

Swiftは4.2です。

ViewController.swift

class ViewController: UIViewController {

    @IBOutlet weak var container:UIView!
    let redView:UIView = UINib(nibName: "RedView", bundle:nil).instantiate(withOwner: self, options: nil)[0] as! UIView
    let blueView:UIView = UINib(nibName: "BlueView", bundle:nil).instantiate(withOwner: self, options: nil)[0] as! UIView
    var changeFlag = false

    override func viewDidLoad() {
        super.viewDidLoad()
        changeView()
    }


    func changeView() {
        let width = self.container.bounds.size.width//containerの横幅を取得
        let height = self.container.bounds.size.height//containerの縦幅を取得
        let frame = CGRect(x:0, y:0, width:width, height:height)//containerの幅に設定

        //フラグによってViewをaddSubView、removeFromSuperviewして入れ替える
        if changeFlag {
            blueView.removeFromSuperview()
            redView.frame = frame
            container.addSubview(redView)
            changeFlag = false
        } else {
            redView.removeFromSuperview()
            blueView.frame = frame
            container.addSubview(blueView)
            changeFlag = true
        }
    }

    @IBAction func click(sender:AnyObject){
        changeView()
    }
}

addSubViewと、removeFromSuperviewを用いてContainerの中にViewを追加したり削除したりし、Viewの入れ替えを実現しました 。

DEMO

demo.gif

このように、ボタンを押したら青と赤のViewが入れ替わります!

全ソース

サンプルコードはこちらに置いてあります!
https://github.com/mii-chang/ChangeViewSample

参考になれば嬉しいです◎!

3
6
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
3
6