コードでUIImageをAutoLayoutする – swift

もくじ

説明

自動レイアウトは、画像に制約を適用することによって実現されます。

 

NSLayoutConstraintを使用します。

 

すべてのデバイスに理想的で美しいデザインを実装することが可能です。

 

以下のコードを試してください。

実装

 

//
//  ViewController.swift
//  test
//
//  Created by ryosuke-hujisawa on 2017/12/06.
//  Copyright © 2017年 ryosuke-hujisawa. All rights reserved.
//  vaaaval@gmail.com

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

let myImageView:UIImageView = UIImageView()
myImageView.backgroundColor = UIColor.red
myImageView.image = UIImage(named:"sample_dog")!
myImageView.translatesAutoresizingMaskIntoConstraints = false
myImageView.layer.borderColor = UIColor.red.cgColor
myImageView.layer.borderWidth = 10
self.view.addSubview(myImageView)

view.removeConstraints(view.constraints)


view.addConstraint(NSLayoutConstraint(
item: myImageView,
attribute: .top,
relatedBy: .equal,
toItem: view,
attribute: .top,
multiplier: 1,
constant:100)

)

view.addConstraint(NSLayoutConstraint(
item: myImageView,
attribute: .centerX,
relatedBy: .equal,
toItem: view,
attribute: .centerX,
multiplier: 1,
constant:0)
)

view.addConstraint(NSLayoutConstraint(
item: myImageView,
attribute: .height,
relatedBy: .equal,
toItem: view,
attribute: .width,
multiplier: 0.5,
constant:40))

view.addConstraint(NSLayoutConstraint(
item: myImageView,
attribute: .width,
relatedBy: .equal,
toItem: view,
attribute: .width,
multiplier: 0.5,
constant:40))

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}
}

 

実行

iPhone SE

スクリーンショット 2017-12-10 9.47.56.png

iPhoneX

スクリーンショット 2017-12-10 9.48.35.png

環境

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

未整理記事