.addTarget과 .addAction은 UIButton을 눌렀을 때 특정 동작(함수, 클로저 등)을 연결하기 위해 사용한다.
.addTarget(_:action:for:)import UIKit
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// addTarget 방식
let targetButton = UIButton(type: .system)
targetButton.setTitle("addTarget 버튼", for: .normal)
targetButton.backgroundColor = .systemBlue
targetButton.setTitleColor(.white, for: .normal)
targetButton.addTarget(self, action: #selector(targetButtonTapped), for: .touchUpInside)
view.addSubview(targetButton)
}
@objc func targetButtonTapped() {
print("✅ addTarget 버튼 눌림")
showAlert()
}
private func showAlert() {
let alert = UIAlertController(title: "버튼", message: "버튼을 눌렸습니다", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "확인", style: .default))
present(alert, animated: true)
}
}
@objc 메서드를 사용해야 함.addAction(_:for:)import UIKit
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// addAction 방식
let actionButton = UIButton(type: .system)
actionButton.setTitle("addAction 버튼", for: .normal)
actionButton.backgroundColor = .systemGreen
actionButton.setTitleColor(.white, for: .normal)
// [weak self] 사용으로 메모리 누수 방지
actionButton.addAction(UIAction { [weak self] _ in
guard let self = self else { return }
print("✅ addAction 버튼 눌림")
self.showAlert()
}, for: .touchUpInside)
view.addSubview(actionButton)
}
private func showAlert() {
let alert = UIAlertController(title: "버튼", message: "버튼을 눌렸습니다", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "확인", style: .default))
present(alert, animated: true)
}
}
self, 변수 등).addAction은 클로저를 사용하기 때문에 self를 강하게 참조할 수 있다.self가 버튼을 가지고 있고, 버튼이 클로저를 가지고 있고,self를 참조하면…💥 순환 참조 발생[weak self]로 self를 약하게 참조하여 해결guard let self = self else { return }로 안전하게 self 사용💡 어떤 걸 써야 할까?
- ViewController의 메서드를 호출하고 싶을 때 / iOS 14 미만 지원 →
addTarget- 간단한 동작, 내부 처리 / 최신 프로젝트 (iOS 14+) →
addAction
| 항목 | addTarget | addAction |
|---|---|---|
| 등장 시기 | 오래됨 (iOS 2+) | 최신 (iOS 14+) |
| 문법 | Selector 기반 | 클로저 기반 |
| 연결 방식 | 메서드 호출 | 클로저 실행 |
| 컨텍스트 캡처 | 불가능 | 가능 (self, 변수 사용 가능) |
| 메모리 누수 위험 | 거의 없음 | [weak self] 필수! |
| 장점 | 오래된 iOS 지원 | Swift스럽고 직관적 |
| 단점 | @objc 필요, 번거로움 | 메모리 관리 주의 필요 |