0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

FrameとBoundsの違いを理解する

Posted at

はじめに

UIKitを触ったときにframeとかboudnsとかで情報が散乱していました。
今回はframe, boundsについて情報を整理します。

環境

Swift 5.4.2
Xcode 12.5.2
macOS Big Sur 11.5.2

frameboundsの違い

画像で説明したらわかりやすかったです。

frameの場合、起点がルートビューの左上です。
一方、boundsの起点は、自身の左上でした。

frameの使用例

ViewController.swift
// X方向の最小値を取得する
view.frame.minX

// X方向の中央値を取得する
view.frame.midX

// X方向の最大値を取得する
view.frame.maxX

// NavigationBarのHeightを取得する
navigationController?.navigationBar.frame.height

// TabBArのHeightを取得する
tabBarController?.tabBar.frame.height

boundsの使用例

ViewController.swift
// スクリーンのサイズを取得する
UIScreen.main.bounds

NavigationBarの下にボタンを追加する

frameを使って、NavigationBarの下にボタンを追加してみます。

ViewController.swift
// NavigationBarのy座標を取得します
let navBarBottom = navigationController.navigationBar.frame.maxY

// Viewの幅を利用して、ボタンの幅を取得します
let buttonWidth = view.bounds.width - 20

// UIButtonを定義する際に、NavigationBarのbottomを利用します
let button = UIButton(frame: CGRect(x: 10, y: navBarBottom + 10, width: buttonWidth, height: 50))

...

view.addSubview(button)

参考リンク

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?