Динамическое изменение размера ячейки TableViewController - PullRequest
0 голосов
/ 15 февраля 2020

В моем проекте у меня есть SignUpViewController, который выглядит следующим образом:

enter image description here

Все textFields настроены - cells в пределах a tableViewController.

TableView:

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: "SignUpEmailCell", for: indexPath) as! SignUpEmailCell
        return cell
    // 2nd cell -> anzeigename
    }else if indexPath.row == 1 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SignUpAnzeigeName", for: indexPath) as! SignUpAnzeigeName
        return cell
    // 3rd cell -> Wishlist-Handle
    }else if indexPath.row == 2 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SignUpHandleCell", for: indexPath) as! SignUpHandleCell
        return cell
    // 4th cell -> passwort textfield
    }else if indexPath.row == 3 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SignUpPasswordCell", for: indexPath) as! SignUpPasswordCell
        return cell
    // 5th cell -> repeat password textfield
    }else if indexPath.row == 4 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SignUpPasswordRepeatCell", for: indexPath) as! SignUpPasswordRepeatCell
        return cell
    // 6th cell -> document label
    }else if indexPath.row == 5 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SignUpDocumentCell", for: indexPath) as! SignUpDocumentCell
        return cell
    }
    // last cell -> signUpButton
    let cell = tableView.dequeueReusableCell(withIdentifier: "SignUpButtonCell", for: indexPath) as! SignUpButtonCell
    return cell
}

Password-Cell: (базовая c структура одинакова для всех ячейка)

    class SignUpPasswordCell: UITableViewCell, UITextFieldDelegate {

    public static let reuseID = "SignUpPasswordCell"

    lazy var eyeButton: UIButton = {
        let v = UIButton()
        v.addTarget(self, action: #selector(eyeButtonTapped), for: .touchUpInside)
        v.setImage(UIImage(named: "eyeOpen"), for: .normal)
        v.translatesAutoresizingMaskIntoConstraints = false
        return v
    }()

    lazy var 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 = .white
        v.placeholderFontScale = 0.8
        v.minimumFontSize = 13
        v.borderStyle = .line
        v.addTarget(self, action: #selector(SignUpPasswordCell.passwordTextFieldDidChange(_:)),for: .editingChanged)
        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

        passwordTextField.delegate = self

        eyeButton.isHidden = true
        passwordTextField.textContentType = .newPassword
        passwordTextField.isSecureTextEntry.toggle()

        setupViews()
    }

    func setupViews(){
        contentView.addSubview(passwordTextField)
        contentView.addSubview(eyeButton)

        passwordTextField.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true
        passwordTextField.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
        passwordTextField.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
        passwordTextField.heightAnchor.constraint(equalToConstant: 60).isActive = true

        eyeButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -5).isActive = true
        eyeButton.centerYAnchor.constraint(equalTo: centerYAnchor, constant: 10).isActive = true
    }

    var check = true
    @objc func eyeButtonTapped(_ sender: Any) {

        check = !check

        if check == true {
            eyeButton.setImage(UIImage(named: "eyeOpen"), for: .normal)
        } else {
            eyeButton.setImage(UIImage(named: "eyeClosed"), for: .normal)
        }
        passwordTextField.isSecureTextEntry.toggle()

            if let existingText = passwordTextField.text, passwordTextField.isSecureTextEntry {
                /* When toggling to secure text, all text will be purged if the user
                 continues typing unless we intervene. This is prevented by first
                 deleting the existing text and then recovering the original text. */
                passwordTextField.deleteBackward()

                if let textRange = passwordTextField.textRange(from: passwordTextField.beginningOfDocument, to: passwordTextField.endOfDocument) {
                    passwordTextField.replace(textRange, withText: existingText)
                }
            }

            /* Reset the selected text range since the cursor can end up in the wrong
             position after a toggle because the text might vary in width */
            if let existingSelectedTextRange = passwordTextField.selectedTextRange {
                passwordTextField.selectedTextRange = nil
                passwordTextField.selectedTextRange = existingSelectedTextRange
            }
    }

    @objc func passwordTextFieldDidChange(_ textField: UITextField) {
            if textField.text == "" {
                self.eyeButton.isHidden = true
            }else {
                self.eyeButton.isHidden = false
            }

    }
}

Проблема:

Я хотел бы иметь возможность показать некоторую дополнительную информацию о некоторых textFields при выборе . Например: когда passwordTextField редактирует, я хотел бы показать требования к паролю прямо под текстовым полем. Но дополнительная информация должна отображаться только во время редактирования или после редактирования. Когда ViewController отображается вначале, оно все равно должно выглядеть как на картинке выше.

Я надеюсь, что моя проблема ясна, и я благодарен за любую помощь :) Дайте мне знать, если вам нужна дополнительная информация / код .

...