1
Help us understand the problem. What are the problem?

posted at

updated at

[iOS] もう二度と調べ直さないためのconvertメソッドに関するメモ

convert to

func convert(_ rect: CGRect, to view: UIView?) -> CGRect

レシーバ(メソッドが呼ばれるUIView)が、引数で渡す view を基準とする座標系のどこへ位置しているかを割り出す
rect にはレシーバのローカル座標 (bounds) を指定する

コード例

let rect = targetView.convert(targetView.bounds, to: baseView)

convert from

func convert(_ rect: CGRect, from view: UIView?) -> CGRect

レシーバ(メソッドが呼ばれるUIView)を基準とする座標系のどの位置に、引数で渡す view が位置しているか割り出す
rect には view のローカル座標 (bounds) を指定する

コード例

let rect = baseView.convert(targetView.bounds, from: targetView)

Swift Playground 用

let baseView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
let someView = UIView(frame: CGRect(x: 10, y: 10, width: 200, height: 200))
let targetView = UIView(frame: CGRect(x: 20, y: 20, width: 100, height: 100))
baseView.addSubview(someView)
someView.addSubview(targetView)

let rect1 = targetView.convert(targetView.bounds, to: baseView)
// -> {x 30 y 30 w 100 h 100}
let rect2 = baseView.convert(targetView.bounds, from: targetView)
// -> {x 30 y 30 w 100 h 100}

参考

https://developer.apple.com/documentation/uikit/uiview/1622504-convert
https://developer.apple.com/documentation/uikit/uiview/1622498-convert

Register as a new user and use Qiita more conveniently

  1. You can follow users and tags
  2. you can stock useful information
  3. You can make editorial suggestions for articles
What you can do with signing up
1
Help us understand the problem. What are the problem?