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をプリントアウト
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は右下に移動してしまいました。
Author And Source
この問題について(wift - frameとboundsの違い), 我々は、より多くの情報をここで見つけました https://qiita.com/Wesley-chu/items/7004ca681bcbcc9b3650著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .