[TIL] UIButton의 .addTarget과 .addAction

박주하·2025년 6월 17일

.addTarget.addActionUIButton을 눌렀을 때 특정 동작(함수, 클로저 등)을 연결하기 위해 사용한다.

.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)
    }
}
  • Objective-C의 Selector 기반으로 오래된 방식
  • @objc 메서드를 사용해야 함
  • Selector를 통해 메서드를 연결
  • target(대상 객체)과 action(메서드 이름)을 따로 전달함

.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)
    }
}
  • Swift 5.3+, iOS 14+에서 사용 가능
  • 클로저 기반 → 코드가 간결하고 직관적
  • target/action 개념이 없어짐
  • context 캡처 가능 (예: self, 변수 등)

🤔 [weak self]를 왜 써야 할까?

  • .addAction은 클로저를 사용하기 때문에 self를 강하게 참조할 수 있다.
    self가 버튼을 가지고 있고, 버튼이 클로저를 가지고 있고,
    → 클로저가 다시 self를 참조하면…💥 순환 참조 발생
    → 메모리 누수
  • [weak self]self를 약하게 참조하여 해결
  • guard let self = self else { return }로 안전하게 self 사용

💡 어떤 걸 써야 할까?

  • ViewController의 메서드를 호출하고 싶을 때 / iOS 14 미만 지원 → addTarget
  • 간단한 동작, 내부 처리 / 최신 프로젝트 (iOS 14+) → addAction

📌 정리

항목addTargetaddAction
등장 시기오래됨 (iOS 2+)최신 (iOS 14+)
문법Selector 기반클로저 기반
연결 방식메서드 호출클로저 실행
컨텍스트 캡처불가능가능 (self, 변수 사용 가능)
메모리 누수 위험거의 없음[weak self] 필수!
장점오래된 iOS 지원Swift스럽고 직관적
단점@objc 필요, 번거로움메모리 관리 주의 필요

0개의 댓글