Swift3 – コードからUIViewを生成する

superViewのsubViewとしてコードからUIViewを生成します

実装

 let TestView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 250, height: 250))
        let bgColor = UIColor.blue
        TestView.backgroundColor = bgColor
        self.view.addSubview(TestView)

全ソース

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()


        let TestView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: 250, height: 250))
        let bgColor = UIColor.blue
        TestView.backgroundColor = bgColor
        self.view.addSubview(TestView)



    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

未整理記事