[swift] 팝업창에서 텍스트 입력을 받는 방법 - Swift PopupDialog 사용법

팝업창은 앱에서 유용하게 사용되며, 사용자로부터 정보를 입력 받을 때 특히 유용합니다. 이번 포스트에서는 Swift에서 팝업창을 사용하여 텍스트 입력을 받는 방법을 알아보겠습니다. 팝업창을 생성하는 데는 Swift PopupDialog 라이브러리를 사용할 것입니다.

1. Swift PopupDialog 라이브러리 설치

먼저, CocoaPods을 사용하여 Swift PopupDialog 라이브러리를 설치해야 합니다. Terminal을 열고 프로젝트 디렉토리로 이동한 다음, 아래 명령어를 실행하세요.

pod init

그리고 Podfile을 열고 아래 코드를 추가하세요.

pod 'PopupDialog'

저장한 후, Terminal에서 다음 명령어를 실행하세요.

pod install

2. 팝업창 생성하기

이제, 팝업창을 생성하는 코드를 작성해보겠습니다. 우선, ViewController.swift 파일을 열고 다음과 같이 코드를 작성하세요.

import PopupDialog

class ViewController: UIViewController, UITextFieldDelegate {

    @IBAction func showPopup(_ sender: UIButton) {
        let title = "텍스트 입력"
        let message = "텍스트를 입력하세요:"
        let popup = PopupDialog(title: title, message: message)

        let buttonOk = DefaultButton(title: "확인", dismissOnTap: true) {
            if let textField = popup.textFields?.first {
                let userInput = textField.text ?? ""
                // 사용자의 입력 값에 대한 처리 로직 추가
                print("사용자 입력: \(userInput)")
            }
        }

        let buttonCancel = CancelButton(title: "취소") {}

        popup.addButtons([buttonOk, buttonCancel])

        // 텍스트 필드 추가
        let textField = UITextField(frame: CGRect(x: 0, y: 0, width: 250, height: 30))
        textField.placeholder = "여기에 입력하세요"
        textField.delegate = self
        popup.addTextField(textField)

        self.present(popup, animated: true, completion: nil)
    }

    // Return 키 눌렀을 때 팝업창 닫기
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.view.endEditing(true)
        return false
    }
}

3. 코드 분석

4. 실행 및 결과 확인

이제, 앱을 실행하여 팝업창이 나타나는지 확인해보세요. “확인” 버튼을 클릭한 후, 입력한 텍스트 값이 콘솔에 출력되는 것을 확인할 수 있습니다.

이러한 방식으로 Swift에서 팝업창을 사용하여 텍스트 입력을 받을 수 있습니다. Swift PopupDialog 라이브러리를 사용하면 간단하고 효율적으로 팝업창을 구현할 수 있습니다.