📦 UIView の使い方

UIView は、UIKit におけるすべての表示要素の土台となる基本クラスです。ラベル、ボタン、イメージなど多くの UI 要素は UIView を継承して作られています。


…読み込み中…

🧱 UIViewの基本

UIView は、画面上の矩形領域を表現し、ユーザーインターフェースの基本的な要素を構築します。背景色や枠線、影などのスタイルを設定できます。

🧱 基本構文

let myView = UIView()
myView.frame = CGRect(x: 50, y: 100, width: 200, height: 100)
myView.backgroundColor = .systemBlue
view.addSubview(myView)

🎨 カスタマイズ

見た目を調整するためのプロパティも多く用意されています。

myView.layer.cornerRadius = 12
myView.layer.borderWidth = 2
myView.layer.borderColor = UIColor.white.cgColor
myView.alpha = 0.9
myView.clipsToBounds = true

👆 タップイベントを受け取る

UIView は直接ボタンのようにアクションを持ちませんが、タップ検出は可能です。

let tap = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
myView.addGestureRecognizer(tap)
myView.isUserInteractionEnabled = true

@objc func viewTapped() {
    print("ビューがタップされました")
}

📐 オートレイアウトを使う

Auto Layout を使用する場合、translatesAutoresizingMaskIntoConstraintsfalse にします。

let customView = UIView()
customView.translatesAutoresizingMaskIntoConstraints = false
customView.backgroundColor = .systemGray

view.addSubview(customView)

NSLayoutConstraint.activate([
  customView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
  customView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
  customView.widthAnchor.constraint(equalToConstant: 150),
  customView.heightAnchor.constraint(equalToConstant: 100)
])

🧩 UIView の主な用途

🧠 UIView に関する知識

🔗 関連リンク