📖 UIButtonの基本
UIButton は、ユーザーがタップできるボタンを提供する UIKit のコンポーネントです。ボタンは、アプリケーションのインターフェースでアクションをトリガーするために使用されます。
🧱 基本構文
let button = UIButton(type: .system)
button.setTitle("タップしてね", for: .normal)
button.frame = CGRect(x: 100, y: 100, width: 200, height: 50)
view.addSubview(button)
🎨 ボタンのカスタマイズ
ボタンの外観をカスタマイズするには、以下のプロパティを使用します。
button.backgroundColor = .systemBlue
button.setTitleColor(.white, for: .normal)
button.layer.cornerRadius = 10
⚡ アクションを追加する
ボタンがタップされたときのアクションを設定するには、addTarget(_:action:for:) メソッドを使用します。
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
@objc func buttonTapped() {
print("ボタンがタップされました")
}
🧪 UIButton.Configuration(iOS 15以降)
iOS 15以降では UIButton.Configuration を使用して簡単にスタイル設定ができます。
var config = UIButton.Configuration.filled()
config.title = "送信"
config.baseBackgroundColor = .systemGreen
config.cornerStyle = .medium
let button = UIButton(configuration: config, primaryAction: UIAction(title: "送信", handler: { _ in
print("送信ボタンタップ")
}))