Swift 4-委托问题,UITextField返回nil

时间:2019-01-08 13:27:14

标签: ios swift delegates

我的代码需要帮助。我在UITextField中有一个UICollectionViewCell。我想访问我的UICollectionViewController的数据。该值返回nil

我正在使用委托方法在类之间传递数据,但是我的值返回nil。我看不出问题出在哪里?希望你们能帮助我。谢谢!

import UIKit
import Firebase


class EditUserProfileController: UICollectionViewController, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate {

weak var editUserProfileCellDelegate: EditUserProfileCell?

let cellId = "cellId"
    super.viewDidLoad()

    setupSaveButton()


    setupNavigationBar()

    collectionView?.register(EditUserProfileCell.self, forCellWithReuseIdentifier: cellId)


}


fileprivate func setupSaveButton() {
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Save", style: .plain, target: self, action: #selector(handleUpdateProfile))

}

    @objc func handleUpdateProfile() {


        editUserProfileCellDelegate?.delegate = self

        guard let name = editUserProfileCellDelegate?.nameTextfield.text, name.count > 0 else { return }
        guard let username = editUserProfileCellDelegate?.usernameTextfield.text, username.count > 0 else { return }
        guard let email = editUserProfileCellDelegate?.emailTextfield.text, username.count > 0 else { return }

        guard let city = editUserProfileCellDelegate?.cityTextfield.text else { return }
        guard let country = editUserProfileCellDelegate?.countryTextfield.text else { return }

        guard let fcmToken = Messaging.messaging().fcmToken else { return }

        guard let uid = Auth.auth().currentUser?.uid else { return }

        let ref = Database.database().reference().child("users")

        let disctionaryValues = ["username": username, "name": name, "email": email, "city": city, "country": country,"fcmToken": fcmToken]

        let values = [uid: disctionaryValues]

        ref.setValue(values) { (err, ref) in
            if let err = err {
                print("Failed to update user:", err)
                return
            }

            print("Succesfully updated user: ", self.user?.username ?? "")

        }

    }

我的UITextField:

import UIKit
import Firebase


class EditUserProfileCell: UICollectionViewCell, 
UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    let nameTextfield: UITextField = {
    let tf = UITextField()

    let attributedText = NSMutableAttributedString(string: "Name", 
    attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 14), NSAttributedString.Key.foregroundColor: UIColor.black])

    tf.attributedPlaceholder = attributedText

    tf.textColor = UIColor.black
    tf.font = UIFont.systemFont(ofSize: 14)
    tf.borderStyle = .none
    tf.layer.backgroundColor = UIColor.white.cgColor
    tf.layer.masksToBounds = false
    tf.layer.shadowColor = UIColor.lightGray.cgColor
    tf.layer.shadowOffset = CGSize(width: 0.0, height: 0.5)
    tf.layer.shadowOpacity = 1.0
    tf.layer.shadowRadius = 0.0

    return tf

}()

我希望在我的文本字段中获得输入以返回,例如名称。但是现在我只得到nil

1 个答案:

答案 0 :(得分:0)

您似乎有点困惑,代表的工作方式。所以我创建了示例示例:

def get_cards(x):
    extra = {'S', 'A','M', 'E', 'G','D'}.difference(set(x))
    x=x.append(pd.Series(list(extra)))
    return ",".join(x.tolist())

temp1.groupby(['Card_x','Country', 'Age', 'Code'])['Card_y'].apply(lambda x: get_cards(x) ).reset_index()

好的,那应该使您更好地了解该问题。现在,让我们将其转换为您的代码。

从声明协议开始

protocol Delegate: class { // declare delegate protocol
    func someFunction()
}

class Cell: UICollectionViewCell {

    weak var delegate: Delegate? // declare delegate variable

    func callDelegate() {
        delegate?.someFuntion() // call method on delegate
    }
}

class ViewController: UICollectionViewController {
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        ...
        cell.delegate = self // set delegate of cell as your view controller
        ...
    }
}

extension ViewController: Delegate { // implement protocol
    func someFunction() { // this method gets called when you call this method on delegate from some cell
    }
}

现在在单元格子类中创建变量,并在文本字段结束编辑时调用委托

protocol EditUserProfileCellDelegate: class {
    func nameSaved(_ name: String)
}

现在让我们为您的视图控制器实现协议

class EditUserProfileCell: UICollectionViewCell, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    weak var delegate: EditUserProfileCellDelegate?
    ...
}

extension EditUserProfileCell: UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField == nameTextField {
            delegate?.nameSaved(textField.text!)
        }
    }
}

最后不要忘记在extension EditUserProfileController: EditUserProfileCellDelegate { func nameSaved(_ name: String) { ... // do something with name } }

中设置单元格的委托
cellForItemAt