43
41

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 5 years have passed since last update.

SwiftでカスタマイズしたViewを追加する方法

Last updated at Posted at 2014-07-23

UIViewControllerのviewのx座標とy座標と高さと幅を、カスタマイズしたViewにパラメータとして渡してViewを生成する方法の覚え書き。

ViewController

ViewController.swift
import UIKit

class ViewController: UIViewController {
                            
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //UIViewController.viewの座標取得
        var x:CGFloat = self.view.bounds.origin.x
        var y:CGFloat = self.view.bounds.origin.y
        
        //UIViewController.viewの幅と高さを取得
        var width:CGFloat = self.view.bounds.width;
        var height:CGFloat = self.view.bounds.height
        
        //上記より画面ぴったりサイズのフレームを生成する
        var frame:CGRect = CGRect(x: x, y: y, width: width, height: height)
        
        //カスタマイズViewを生成
        var myVeiw:SampleView = SampleView(frame: frame)
        
        //カスタマイズViewを追加
        self.view.addSubview(myVeiw)
    }
}

カスタマイズしたView

SampleView.swift
import Foundation
import UIKit

class SampleView :UIView{
    init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.greenColor()
        
    }
}

余談だが、パラメータの渡し方(パラメータ名を付けたり付けなかったり)に、自分はどうしても慣れない。

43
41
2

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
43
41

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?