16
17

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でカスタマイズしたImageViewを追加する方法

Posted at

今回は、UIImageViewを継承したカスタマイズしたViewクラスを追加してみた。

ViewController

ViewController.swift
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)
        
        //カスタマイズImageViewを生成
        var myView:SampleImageView = SampleImageView(frame: frame)
        //var myView:SampleView = SampleView(frame: frame)
        
        //カスタマイズViewを追加
        self.view.addSubview(myView)
    }

}

画像のインポート

読み込む画像は、Images.xcassetsファイルにインポートしておく。

スクリーンショット 2014-07-23 18.28.26.png

カスタマイズしたImageView

SampleImageView.swift
import Foundation
import UIKit

class SampleImageView : UIImageView{
    init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor.blueColor()
        var img:UIImage = UIImage(named: "snowman")
        self.image = img
        self.contentMode = UIViewContentMode.Center
    }
}

出力結果
スクリーンショット 2014-07-23 18.29.17.png

16
17
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
16
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?