LoginSignup
0
1

More than 3 years have passed since last update.

画面サイズに合わせてパーツの大きさを変える(初心者向け)

Posted at

こんにちは。プログラミング初心者兼Swift初心者です。

storyboardのオートレイアウトで画面サイズが変わっても、部品の位置はある程度決めることができますが、大きさを変えることができないので「小さい画面だとキツキツ、大きい画面だと余白ができる」なんてことがありました。
そこで画面サイズを元にして、動的に部品サイズを変更することができたのでコードを載せておきます。

    //今回はImageViewの大きさを変更します
    @IBOutlet weak var imageView: UIImageView!
    //画面サイズを取得
    let screenSize = UIScreen.main.bounds.size

    override func viewDidLoad() {
        super.viewDidLoad()

        //imageViewの横幅を画面サイズの80%にする
        let ivWidth = screenSize.width * 0.8
        //imageViewの縦幅は横幅の0.666....倍
        let ivHeight = ivWidth * 0.66
        //あとから左右中央にするのでy座標と大きさをここで決める
        imageView.frame = CGRect(x: 0,
                                 y: screenSize.height / 6,
                                 width: ivWidth,
                                 height: ivHeight)
        //左右中央に指定
        imageView.center.x = screenSize.width / 2
    }

簡略化するためにUIImageViewのアスペクト比や画面サイズを元に定数で書いていますが、変数に格納したほうがいいですね笑

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