Заполните UITableView пользовательскими ячейками - PullRequest
1 голос
/ 28 января 2020

Я пытаюсь создать экран регистрации внутри своего приложения, и хотя использование TableView - лучший способ реализовать это.

Моя проблема в том, что мои пользовательские ячейки не отображают то, что должны ..

Это мой SignUpTableView-класс:

    class SignUpTableView: UIView, UITableViewDelegate, UITableViewDataSource {

    let emailTextField: CustomTextField = {
            let v = CustomTextField()
            v.borderActiveColor = .white
            v.borderInactiveColor = .white
            v.textColor = .white
            v.font = UIFont(name: "AvenirNext-Regular", size: 17)
            v.placeholder = "Email-Adresse"
            v.placeholderColor = .gray
            v.placeholderFontScale = 1
            v.clearButtonMode = .always
            v.minimumFontSize = 13
            v.borderStyle = .line
            v.autocapitalizationType = .none
            v.translatesAutoresizingMaskIntoConstraints = false
            return v
        }()


        let wishlistHandleTextField: CustomTextField = {
            let v = CustomTextField()
            v.borderActiveColor = .white
            v.borderInactiveColor = .white
            v.textColor = .white
            v.font = UIFont(name: "AvenirNext-Regular", size: 17)
            v.placeholder = "Wishlist-Handle"
            v.placeholderColor = .gray
            v.placeholderFontScale = 1
            v.clearButtonMode = .always
            v.minimumFontSize = 13
            v.borderStyle = .line
            v.autocapitalizationType = .none
            v.translatesAutoresizingMaskIntoConstraints = false
    //        v.leftView = handleLeftView
    //        v.leftViewMode = .always
            return v
        }()

        let anzeigeNameTextField: CustomTextField = {
            let v = CustomTextField()
            v.borderActiveColor = .white
            v.borderInactiveColor = .white
            v.textColor = .white
            v.font = UIFont(name: "AvenirNext-Regular", size: 17)
            v.placeholder = "Anzeigename: z.B. dein Vorname"
            v.placeholderColor = .gray
            v.placeholderFontScale = 1
            v.clearButtonMode = .always
            v.minimumFontSize = 13
            v.borderStyle = .line
            v.autocapitalizationType = .none
            v.translatesAutoresizingMaskIntoConstraints = false
            return v
        }()



        let passwordTextField: CustomTextField = {
            let v = CustomTextField()
            v.borderActiveColor = .white
            v.borderInactiveColor = .white
            v.textColor = .white
            v.font = UIFont(name: "AvenirNext-Regular", size: 17)
            v.placeholder = "Passwort"
            v.placeholderColor = .gray
            v.placeholderFontScale = 1
            v.minimumFontSize = 13
            v.borderStyle = .line
            v.addTarget(self, action: #selector(SignUpViewController.passwordTextFieldDidChange(_:)),for: .editingChanged)
            v.translatesAutoresizingMaskIntoConstraints = false
            return v
        }()

        let passwordWiederholenTextField: CustomTextField = {
            let v = CustomTextField()
            v.borderActiveColor = .white
            v.borderInactiveColor = .white
            v.textColor = .white
            v.font = UIFont(name: "AvenirNext-Regular", size: 17)
            v.placeholder = "Passwort wiederholen"
            v.placeholderColor = .gray
            v.placeholderFontScale = 1
            v.minimumFontSize = 13
            v.borderStyle = .line
            v.addTarget(self, action: #selector(SignUpViewController.passwordTextFieldDidChange(_:)),for: .editingChanged)
            v.translatesAutoresizingMaskIntoConstraints = false
            return v
        }()


        let signUpButton: TransitionButton = {
            let v = TransitionButton()
            v.translatesAutoresizingMaskIntoConstraints = false
            v.setTitle("Registrieren", for: .normal)
            v.titleLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 15)
            v.titleLabel?.textColor = .white
            v.setTitleColor(.white, for: .normal)
            v.backgroundColor = UIColor.darkGray
            v.layer.cornerRadius = 3
//            v.addTarget(self, action: #selector(signUpButtonTapped(_:)), for: .touchUpInside)
            return v
        }()

        let documentsLabel: UILabel = {
            let v = UILabel()
            v.text = "Durch Klicken auf 'Registrieren' akzeptiere ich die Nutzungbedingungnen und die Datenschutzrichtlinien."
            v.font = UIFont(name: "AvenirNext-Regular", size: 13)
            v.textColor = .lightGray
            v.textAlignment = .center
            v.numberOfLines = 0
            v.translatesAutoresizingMaskIntoConstraints = false
            return v
        }()

    var tableView = UITableView()


    override init(frame: CGRect) {
        super.init(frame: frame)

        tableView.backgroundColor = .clear

// disable didSelectAt
        self.tableView.allowsSelection = false


//        self.tableView.separatorStyle = .none

        self.tableView.register(SignUpTextfieldCell.self, forCellReuseIdentifier: SignUpTextfieldCell.reuseID)
        self.tableView.register(SignUpDocumentCell.self, forCellReuseIdentifier: SignUpDocumentCell.reuseID)
        self.tableView.register(SignUpButtonCell.self, forCellReuseIdentifier: SignUpButtonCell.reuseID)

        tableView.delegate = self
        tableView.dataSource = self


        tableView.translatesAutoresizingMaskIntoConstraints = false

        self.addSubview(tableView)

        tableView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
        tableView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
        tableView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - Table view data source

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 7
    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 1st cell -> email textfield
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SignUpTextfieldCell", for: indexPath) as! SignUpTextfieldCell
            cell.theTextField = self.emailTextField
            return cell
        // 2nd cell -> anzeigename
        }else if indexPath.row == 1 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SignUpTextfieldCell", for: indexPath) as! SignUpTextfieldCell
            cell.theTextField = self.anzeigeNameTextField
            return cell
        // 3rd cell -> Wishlist-Handle
        }else if indexPath.row == 2 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SignUpTextfieldCell", for: indexPath) as! SignUpTextfieldCell
            cell.theTextField = self.wishlistHandleTextField
            return cell
        // 4th cell -> passwort textfield
        }else if indexPath.row == 3 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SignUpTextfieldCell", for: indexPath) as! SignUpTextfieldCell
            cell.theTextField = self.passwordTextField
            return cell
        // 5th cell -> repeat password textfield
        }else if indexPath.row == 4 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SignUpTextfieldCell", for: indexPath) as! SignUpTextfieldCell
            cell.theTextField = self.passwordWiederholenTextField
            return cell
        // 6th cell -> document label
        }else if indexPath.row == 5 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "SignUpDocumentCell", for: indexPath) as! SignUpDocumentCell
            cell.documentLabel = self.documentsLabel
            return cell
        }
        // last cell -> signUpButton
        let cell = tableView.dequeueReusableCell(withIdentifier: "SignUpButtonCell", for: indexPath) as! SignUpButtonCell
        cell.signUpButton = self.signUpButton
        return cell
    }

}

Пользовательские ячейки (это мой SignUpTextfieldCell, остальные почти то же самое)

    class SignUpTextfieldCell: UITableViewCell {

    public static let reuseID = "SignUpTextfieldCell"

    var theTextField: UITextField = {
        let v = UITextField()
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()

    required init?(coder: NSCoder) {fatalError("init(coder:) has not been implemented")}

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        self.backgroundColor = .clear

        setupViews()
    }

    func setupViews(){
        contentView.addSubview(theTextField)

        theTextField.topAnchor.constraint(equalTo: topAnchor).isActive = true
        theTextField.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        theTextField.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        theTextField.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
    }
}

Когда я добавляю экземпляр SignUpTableView к своему SignUpViewController, он отображается, но с пустыми ячейками. Я попытался установить backgroundColor для первого cell, и это работает. Но почему мои Textfields/Label/Button не отображаются?

Ответы [ 3 ]

0 голосов
/ 28 января 2020

Попробуйте добавить высоту для UITableView, а также попробуйте

yourTableView.rowHeight = 44
yourTableView.estimatedRowHeight = UITableView.automaticDimension
0 голосов
/ 28 января 2020

Я решил проблему, просто создав все textFiedlds/label/button в каждом CustomCell. Теперь у меня 5 cells с textfield внутри, и я подумал, что могу упростить это с помощью кода выше, но он не работает.

0 голосов
/ 28 января 2020

я думаю, вы должны установить противопоказания для этих элементов в ячейке, пожалуйста, попытайтесь использовать файл xib для создания этой ячейки? если вам не нравится xib, посмотрите на эту программно настраиваемую ячейку

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...