LoginSignup
KAinone
@KAinone

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

TextFieldのtextが取得できない

解決したいこと

名前とメールアドレス、パスワードを入力する3つのtextFieldと、サインアップボタンを配置し、Firebaseを使ったサインアップ機能を作りました。3つのtextFieldのいずれかが空白の場合はサインアップボタンを押しても、HUDで警告を出しreturnするようにしています。シミュレーターで実行してみたところ、3つのtextFieldが全て入力されていても、textField.textがnil判定になっているのか、サインアップできずにHUDが表示されてしまいました。
原因がわかる方がいらっしゃいましたらご教授ください。

発生している問題・エラー

Screenshot 2023-11-09 at 21.28.45.png

シミュレーターでサインアップボタンを押した直後

該当するソースコード

func signUpButton() {
        
        let signUpViewCell = SignUpViewCell()
        
        if let artistName = signUpViewCell.artistNameTextField.text, let mailAddress = signUpViewCell.mailAddressTextField.text, let password = signUpViewCell.passwordTextField.text {
            
            if artistName.isEmpty || mailAddress.isEmpty || password.isEmpty {
                
                HUD.flash(.labeledError(title: "Sign Up Failed", subtitle: "必要項目を入力してください"), delay: 1)
                
                return
            }
            
            HUD.show(.progress)
            
            Auth.auth().createUser(withEmail: mailAddress, password: password) {authResult, error in
                
                if error != nil {
                    
                    HUD.flash(.labeledError(title: "Sign Up Failed", subtitle: "ユーザー作成に失敗しました"), delay: 1)
                    
                    return
                }
                
            }
            
            let currentUser = Auth.auth().currentUser
            
            if let user = currentUser {
                
                let changeRequest = user.createProfileChangeRequest()
                
                changeRequest.displayName = artistName
                
                changeRequest.commitChanges {error in
                    
                    if error != nil {
                        
                        HUD.flash(.labeledError(title: "Sign Up Failed", subtitle: "アーティスト名の設定に失敗しました"), delay: 1)
                        
                        return
                    }
                    
                    HUD.hide()
                    
                    self.dismiss(animated: true)
                    
                }
                
            }
            
        }
        
    }
0

1Answer

let signUpViewCell = SignUpViewCell()

signUpButton関数の先頭で、SignUpViewCellの新たなインスタンスを生成していて、そのインスタンスに対して入力チェックを行っています。生成したばかりのインスタンスのため、何も入っていないということでしょう。

サインインのビューを表示した時のインスタンスを使ってチェックする必要があります。
表示する方のコードを見せてください。

2

Comments

  1. @KAinone

    Questioner

    ご返答いただきありがとうございます。
    生成したばかりのインスタンスだから何も入っていなかったのですね。
    今回の該当コードがサインアップ(新規登録)画面なので、サインインのビューというのがどれにあたるかわからないのですが、SignUpViewControllerのtableViewにSignUpViewCellをregisterする形をとっているので、そちらの全体コードを載せさせていただきます。
    正しく入力チェックするための改善点がありましたらご教授ください。よろしくお願いします。

    SignUpViewController

    class SignUpViewController: UITableViewController, SignUpViewCellDelegate {
    
    
        override func viewDidLoad() {
            
            super.viewDidLoad()
            
            tableView.delegate = self
            tableView.dataSource = self
            
            tableView.register(SignUpViewCell.self, forCellReuseIdentifier: "signUpViewCell")
        }
    
    //略
    
        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "signUpViewCell") as! SignUpViewCell
            
            cell.signUpViewCellDelegate = self
            
            return cell
        }
    
    
        func signUpButton() {
            
            //先述
        }
    
    
    }
    

    SignUpVIewCell

    protocol SignUpViewCellDelegate: AnyObject {
        
        func signUpButton()
    }
    
    
    class SignUpViewCell: UITableViewCell, UITextFieldDelegate {
    
    
        weak var signUpViewCellDelegate: SignUpViewCellDelegate? = nil
        
        let artistNameTextField = UITextField()
        let mailAddressTextField = UITextField()
        let passwordTextField = UITextField()
        let signUpButton = UIButton()
    
    
        override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
            
            super.init(style: style, reuseIdentifier: reuseIdentifier)
            
            artistNameTextField.delegate = self
            mailAddressTextField.delegate = self
            passwordTextField.delegate = self
            
            artistNameTextField.tag = 0
            mailAddressTextField.tag = 1
            passwordTextField.tag = 2
            
            setupSubviews()
            
            signUpButton.addTarget(self, action: #selector(handleSignUpButton(_:)), for: .touchUpInside)
        }
        
        
        required init?(coder: NSCoder) {
            
            fatalError("init(coder:) has not been implemented")
        }
    
    
        override func layoutSubviews() {
            
            super.layoutSubviews()
            
            artistNameTextField.textContentType = .username
            artistNameTextField.returnKeyType = .next
            artistNameTextField.clearButtonMode = .whileEditing
            
            mailAddressTextField.keyboardType = .emailAddress
            mailAddressTextField.textContentType = .emailAddress
            mailAddressTextField.returnKeyType = .next
            mailAddressTextField.clearButtonMode = .whileEditing
            
            passwordTextField.keyboardType = .asciiCapable
            passwordTextField.textContentType = .newPassword
            passwordTextField.isSecureTextEntry = true
            passwordTextField.returnKeyType = .done
            
            signUpButton.setTitle("サインアップ", for: .normal)
            signUpButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 20)
        }
    
    
        func setupSubviews() {
            
            contentView.addSubview(artistNameTextField)
            contentView.addSubview(mailAddressTextField)
            contentView.addSubview(passwordTextField)
            contentView.addSubview(signUpButton)
            
            artistNameTextField.snp.makeConstraints {
                
                $0.width.equalToSuperview().multipliedBy(0.8)
                $0.height.equalTo(40)
                $0.centerX.equalToSuperview()
                $0.top.equalToSuperview().offset(200)
            }
    
            //略
            
        }
    
    
        override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
            
            self.endEditing(true)
        }
    
    
        func textFieldDidChangeSelection(_ textField: UITextField) {
            
            guard let mailAddress = mailAddressTextField.text else { return }
            guard let password = passwordTextField.text else { return }
            
            mailAddressTextField.text = mailAddress.removingWhiteSpace()
            passwordTextField.text = password.removingWhiteSpace()
        }
    
    
        @objc func handleSignUpButton(_ sender: UIButton) {
            
            signUpViewCellDelegate?.signUpButton()
        }
    
    
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            
            switch textField.tag {
                
            case 0:
                mailAddressTextField.becomeFirstResponder()
                
            case 1:
                passwordTextField.becomeFirstResponder()
                
            case 2:
                passwordTextField.resignFirstResponder()
                
            default:
                break
            }
            
            return true
        }
    
    
    }
    
  2. 「サインアップ」ボタンがタップされた時に、そのSignUpViewCellのインスタンスを引数で渡せば良いです。
    以下の4箇所を変更します(-の行を、+の行に変更する)。

    SignUpViewController.swift
    -   func signUpButton() {        
    -       let signUpViewCell = SignUpViewCell()
    +   func signUpButton(_ sender: SignUpViewCell) {        
    +       let signUpViewCell = sender
    
    SignUpVIewCell.swift
    protocol SignUpViewCellDelegate: AnyObject {   
    -   func signUpButton()
    +   func signUpButton(_ sender: SignUpViewCell)
    }
    
    
        @objc func handleSignUpButton(_ sender: UIButton) {
    -       signUpViewCellDelegate?.signUpButton()       
    +       signUpViewCellDelegate?.signUpButton(self)
        }
    
  3. @KAinone

    Questioner

    非常にわかりやすく記載していただきありがとうございます。
    引数とは思いつきませんでした、、、
    教えていただいた通りに変更しシミュレーターで実行してみたところ上手く動きました。
    ご丁寧に教えていただき感謝します。ありがとうございました。

  4. お役に立ててなによりです✌️

Your answer might help someone💌