wift - frameとboundsの違い


はじめに

初回の投稿ですが、お手柔に宜しくお願いします〜
ところで、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をプリントアウト

結果は以下:

boundsは自分自身が基準なので、特に設定してない場合x、y両方0です。

画像で理解

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)")

結果はこうなってます:

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

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

実行してみたら

原因は、yellowViewの原点座標は(-20,-20)になり、redViewの原点座標は(0,0)のままなので、redViewは右下に移動してしまいました。