iOS 앱 프로그래밍

[iOS Dev] Add UIButton, Alert programmatically

후추멍멍이 2021. 11. 18. 14:45
iOS App Development Study - Study about Alert 
iOS 어플 개발 공부 - 얼럿 공부
  • 개발 환경 : MacBook Pro (13-inch, M1, 2020), Monterey
  • XCode : Version 13.1 (13A1030d), Swift5
  • 시뮬레이터 : iPhone 11

ViewController

import UIKit

class ViewController: UIViewController {

	let button = UIButton(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
	
	override func viewDidLoad() {
		super.viewDidLoad()
		
		// set the btn
		button.center = view.center
		button.backgroundColor = .black
		button.setTitle("Alert Test Button", for: .normal)
		button.addTarget(self, action:#selector(buttonClicked), for: .touchUpInside)
		
		self.view.addSubview(button)
	}
	@objc func buttonClicked() {
		// if clicked btn, present alert
		let alert = UIAlertController(title: "Show Alert", message: "Hello World!", preferredStyle: .alert)
		alert.addAction(UIAlertAction(title: "CANCEL", style: .cancel, handler: nil))
		alert.addAction(UIAlertAction(title: "DEFAULT", style: .default, handler: nil))
		alert.addAction(UIAlertAction(title: "DESTRUCTIVE", style: .destructive, handler: nil))
		
		present(alert, animated: true, completion: nil)
	}
}