LoginSignup
0
2

【Swift】Cartographyを使ってコードだけで簡単に画像を実装

Last updated at Posted at 2021-04-19

Swiftの超便利ライブラリ「Cartography」を使ってコードだけで画像を実装する方法をご紹介します。

感覚としてはCSSみたいに実装できます。

podで導入する際はPodfileに

pod 'Cartography'

を書いて
初めてPodをインストールするプロジェクトなら

pod install

Pod installしてあるプロジェクトなら

pod update

を実行。

実装するSwiftのコードは以下の通り。

import UIKit
import Cartography

(中略)

let Image : UIImage = UIImage(named:"sample")!
let imageView = UIImageView(image:Image)
self.view.addSubview(imageView)
constrain(imageView) { image in
    image.width  == 50
    image.height == 50
    image.centerX == image.superview!.centerX
    image.centerY == image.superview!.centerY
}

コードの順番(特にaddsubview)とか間違えるとエラーになるのでご注意ください。

補足
・superviewとは親要素のこと(今回はself.viewのこと)
・centerXとは中心のX軸の値
・centerYとは中心のY軸の値

Swiftのお役立ち情報

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