LoginSignup
1
2

More than 3 years have passed since last update.

Swift - frameとboundsの違い

Last updated at Posted at 2021-04-18

はじめに

初回の投稿ですが、お手柔に宜しくお願いします〜
ところで、frameとboundsの違いについて結構最近やっとわかった、記録しておこうかなと思います。

frameとは

frameはsuperviewが基準にして相対的な座標・大きさを返すプロパティ

boundsとは

boundsは要素自身が基準にして相対的な座標・大きさを返すプロパティ

コードで理解

sample.swift
let yellowView: UIView = UIView()

yellowView.backgroundColor = UIColor.yellow

yellowView.frame = CGRect(x: 50, y: 50, width: 100, height: 100)

self.view.addSubview(yellowView)

// Yellow ViewのFrameとBoundsをプリントアウト
print("Yellow View Frame: \(yellowView.frame)") // Frameをプリントアウト
print("Yellow View Bounds: \(yellowView.bounds)") // Boundsをプリントアウト

結果は以下:
截圖 2021-04-18 21.24.05.png
boundsは自分自身が基準なので、特に設定してない場合x、y両方0です。

画像で理解

截圖 2021-04-18 19.16.00.png

boundsを設定した場合はどうなりますか

yellowViewにredViewをaddし、さらにyellowViewのboundsのx、yを(-20,-20)にしてみましょう。

sample2.swift
let redView: UIView = UIView()

redView.backgroundColor = UIColor.red

redView.frame = CGRect(x: 0, y: 0, width: 50, height: 50)

yellowView.addSubview(redView)

print("Red View Frame: \(redView.frame)")
print("Red View Bounds: \(redView.bounds)")

結果はこうなってます:
Simulator Screen Shot - iPhone 8 - 2021-04-18 at 21.51.31.png
截圖 2021-04-18 21.46.59.png

また、yellowViewのboundsのx、yを(-20,-20)にしてみましょう。

sample3.swift
yellowView.bounds = CGRect(x: -20, y: -20, width: 100, height: 100)

実行してみたら
Simulator Screen Shot - iPhone 8 - 2021-04-18 at 21.55.35.png
原因は、yellowViewの原点座標は(-20,-20)になり、redViewの原点座標は(0,0)のままなので、redViewは右下に移動してしまいました。

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