Изменить UILable, скрыть inputAccessoryView [swift 5] - PullRequest
1 голос
/ 07 февраля 2020

Помогите мне решить эту проблему. У меня есть tableView, ячейки содержат UILable Мне нужно показать клавиатуру с inputAccessoryView (с textField) при прикосновении к ячейке или метке. После редактирования передайте текст из textField в UILable в ячейке, закройте клавиатуру и полностью скрыте inputAccessoryView.

Теперь я решаю эту проблему с inputAccessoryView, я textField.becomeFirstResponder (), но после редактирования inputAccessoryView остается видимый.

!!! Мне нужно, чтобы inputAccessoryView был полностью скрыт до и после редактирования. Не на экране. теперь до и после редактирования он находится внизу экрана

до редактирования

во время редактирования

однажды отредактированный

Вот мой код.

import UIKit

class TableViewController: UITableViewController {

    override var canBecomeFirstResponder: Bool {
        return true
    }

    var customInputView: UIView!
    var sendButton: UIButton!
    var addMediaButtom: UIButton!
    let textField = FlexibleTextView()


    override var inputAccessoryView: UIView? {

        if customInputView == nil {
            customInputView = CustomView()
            customInputView.backgroundColor = UIColor.groupTableViewBackground
            textField.placeholder = "I'm gonna grow in height."
            textField.font = .systemFont(ofSize: 15)
            textField.layer.cornerRadius = 5

            customInputView.autoresizingMask = .flexibleHeight

            customInputView.addSubview(textField)

            sendButton = UIButton(type: .system)
            sendButton.isEnabled = true
            sendButton.titleLabel?.font = UIFont.systemFont(ofSize: 16)
            sendButton.setTitle("Send", for: .normal)
            sendButton.contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
            sendButton.addTarget(self, action: #selector(handleSend), for: .touchUpInside)
            customInputView?.addSubview(sendButton)

            addMediaButtom = UIButton(type: .custom)
            addMediaButtom.setImage(UIImage(imageLiteralResourceName: "addImage").withRenderingMode(.alwaysTemplate), for: .normal)
            addMediaButtom.isEnabled = true
            //addMediaButtom.titleLabel?.font = UIFont.systemFont(ofSize: 16)
           // addMediaButtom.setTitle("Media", for: .normal)
            addMediaButtom.contentEdgeInsets = UIEdgeInsets(top: 9, left: 0, bottom: 5, right: 0)
            addMediaButtom.addTarget(self, action: #selector(handleSend), for: .touchUpInside) 
            customInputView?.addSubview(addMediaButtom)

            textField.translatesAutoresizingMaskIntoConstraints = false
            sendButton.translatesAutoresizingMaskIntoConstraints = false
            addMediaButtom.translatesAutoresizingMaskIntoConstraints = false
            sendButton.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: NSLayoutConstraint.Axis.horizontal)
            sendButton.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: NSLayoutConstraint.Axis.horizontal)

            addMediaButtom.setContentHuggingPriority(UILayoutPriority(rawValue: 1000), for: NSLayoutConstraint.Axis.horizontal)
            addMediaButtom.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 1000), for: NSLayoutConstraint.Axis.horizontal)

            textField.maxHeight = 80

            addMediaButtom.leadingAnchor.constraint(
                equalTo: customInputView.leadingAnchor,
                constant: 8
                ).isActive = true

            addMediaButtom.trailingAnchor.constraint(
                equalTo: textField.leadingAnchor,
                constant: -8
                ).isActive = true

          /*  addMediaButtom.topAnchor.constraint(
                equalTo: customInputView.topAnchor,
                constant: 8
                ).isActive = true
            */
            addMediaButtom.bottomAnchor.constraint(
                equalTo: customInputView.layoutMarginsGuide.bottomAnchor,
                constant: -8
                ).isActive = true

            textField.trailingAnchor.constraint(
                equalTo: sendButton.leadingAnchor,
                constant: 0
                ).isActive = true

            textField.topAnchor.constraint(
                equalTo: customInputView.topAnchor,
                constant: 8
                ).isActive = true

            textField.bottomAnchor.constraint(
                equalTo: customInputView.layoutMarginsGuide.bottomAnchor,
                constant: -8
                ).isActive = true

            sendButton.leadingAnchor.constraint(
                equalTo: textField.trailingAnchor,
                constant: 0
                ).isActive = true

            sendButton.trailingAnchor.constraint(
                equalTo: customInputView.trailingAnchor,
                constant: -8
                ).isActive = true

            sendButton.bottomAnchor.constraint(
                equalTo: customInputView.layoutMarginsGuide.bottomAnchor,
                constant: -8
                ).isActive = true
        }
        return customInputView
    }

    @objc func handleSend() {
        print("works")

        self.textField.resignFirstResponder()

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.keyboardDismissMode = .interactive

        // Uncomment the following line to preserve selection between presentations
         self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
         self.navigationItem.rightBarButtonItem = self.editButtonItem


    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      return 0

    }




    @IBAction func test(_ sender: Any) {
        textField.becomeFirstResponder()
    }

}

class CustomView: UIView {

    // this is needed so that the inputAccesoryView is properly sized from the auto layout constraints
    // actual value is not important

    override var intrinsicContentSize: CGSize {
        return CGSize.zero
    }
}

Ответы [ 2 ]

0 голосов
/ 07 февраля 2020

Чтобы избавиться от вспомогательного представления при нажатии кнопки «Отправить», необходимо предотвратить повторное появление tableView в качестве первого респондента.

Добавьте это в свой класс:

var bEditing: Bool = false

затем измените canBecomeFirstResponder() и handleSend():

override var canBecomeFirstResponder: Bool {
    return !bEditing
}

@objc func handleSend() {
    print("works")

    bEditing = true
    self.textField.resignFirstResponder()

    bEditing = false
}
0 голосов
/ 07 февраля 2020

Вы можете добавить inputAccessoryView для каждого текстового поля. Чем он появится только при вводе текста через текущее текстовое поле.

Чтобы установить его, используйте:

textfield.inputAccessoryView = customView

Если вы хотите удалить его, используйте его (но это не нужно)

textfield.inputAccessoryView = nil

, чтобы скрыть его.

PS Лучше создать сложный вид с помощью xib-view.

...