简体   繁体   English

在Swift 4中,UITextField不会在UITableViewCell中结束编辑

[英]UITextField doesn't end editing in a UITableViewCell in Swift 4

I am still new to swift and I would ask you for advice. 我还是个新手,请教一下。 Thank you in advance and sorry for my bad English. 预先感谢您,我的英语不好。

My goal is: 我的目标是:

User tap edit button in the table's row. 用户点击表格行中的编辑按钮。 UITextField appears instead cell. 出现UITextField而不是单元格。 After entering value and pressing Return key UITextField disappears again and cell is recalculated. 输入值并按Return键后, UITextField再次消失,并重新计算单元格。

editButton pressed -> hide priceCell & show UITextField & show keyboard & start editing/entering value (blinking cursor) -> stop editing/entering value execute by pressing Return key -> hide UITextField & shows priceCell & save entered value into array & reload edited row 按下editButton >隐藏priceCell &显示UITextField &显示键盘并开始编辑/输入值(闪烁的光标)->通过按Return键停止编辑/输入值执行->隐藏UITextField &显示priceCell &将输入的值保存到数组中并重新加载已编辑行

I use this answer as starting blueprint. 我用这个答案作为开始的蓝图。

I would like to also use .decimalPad keyboard to easier entering numeric value and limit user to use only numbers (and decimal point), but this exclude use Return key as stop editing, am I right? 我也想使用.decimalPad键盘来更容易地输入数字值,并限制用户仅使用数字(和小数点),但这不包括将Return键用作停止编辑,对吗?

I found this possible solution, but it seems to me complex for my problem... 我找到可能的解决方案,但对我来说,这似乎很复杂...

my ViewController: 我的ViewController:

import UIKit

class PortfolioViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, PortfolioCellDelegate {    

    let getData = GetData()

    ...

    override func viewDidLoad() {
        super.viewDidLoad()

        cellTableView.delegate = self
        cellTableView.dataSource = self

        cellTableView.register(UINib(nibName: "PortfolioCell", bundle: nil), forCellReuseIdentifier: "portfolioCell")

        self.currencyControl.selectedSegmentIndex = MyVariables.currencyControlSelected

    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let coinCell = tableView.dequeueReusableCell(withIdentifier: "portfolioCell", for: indexPath) as! PortfolioCell

        ...

        coinCell.delegate = self

        return coinCell
    }

    ...


    func portfolioButtonPressed(coinCell: PortfolioCell) {
        let indexPath = self.cellTableView.indexPathForRow(at: coinCell.center)!
        let selectedCell = cellTableView.cellForRow(at: indexPath) as! PortfolioCell

        selectedCell.priceCell.isHidden = true
        selectedCell.textCell.isHidden = false

        selectedCell.textCell.delegate = self

        func textFieldDidEndEditing(textField: UITextField) {
            let owned: Double = Double(textField.text!)!

            if owned >= 0 {
                MyVariables.dataArray[indexPath.row].ownedCell = owned
            } else {
                MyVariables.dataArray[indexPath.row].ownedCell = 0.00
            }

            selectedCell.priceCell.isHidden = false
            selectedCell.textCell.isHidden = true

            self.cellTableView.reloadData()
        }

        func textFieldShouldReturn(textField: UITextField) -> Bool {
            selectedCell.textCell.resignFirstResponder()
            return true
        }
    }
    ...
}

my custom cell: 我的自定义单元格:

import UIKit

protocol PortfolioCellDelegate {
    func portfolioButtonPressed(coinCell: PortfolioCell)
}

class PortfolioCell: UITableViewCell {

    var delegate: PortfolioCellDelegate?

    ...

    @IBAction func editCellPressed(_ sender: UIButton) {
     delegate?.portfolioButtonPressed(coinCell: self)
    }
    ...
}

在此处输入图片说明

For now when button is pressed proper UITextField shows, but don't dismiss after Return key is pressed. 现在,当按下按钮时,会显示正确的UITextField ,但在按下Return键后不要关闭。

Or should I change it completely and use tap gestures? 还是应该完全更改它并使用点击手势?

To end editing in any kind of scrollView, simply use this 要结束任何一种scrollView的编辑,只需使用此

cellTableView.keyboardDismissMode = .onDrag

or 要么

cellTableView.keyboardDismissMode = .interactive

It will hide keyboard when you interact with the tableView 与tableView交互时,它将隐藏键盘

For number keypad you can add toolbar as a textField's inputAccessoryView. 对于数字小键盘,您可以将工具栏添加为textField的inputAccessoryView。 On toolbar add cancel button to dismiss keyboard. 在工具栏上,添加取消按钮以关闭键盘。

There is two way to go: 有两种方法:

1.) Delegate 2.) IQKeyboardManager 1.)委托2.)IQKeyboardManager

1.) Use UITextFieldDelegate 1.)使用UITextFieldDelegate

There is one particular callback named "textFieldShouldEndEditing" In this method, return true. 有一个名为“ textFieldShouldEndEditing”的特定回调。在此方法中,返回true。

2.) User the IQKeyboardManager one liner library. 2.)使用IQKeyboardManager一个衬垫库。 This library manages all the TextFields and scrollviews automatically. 该库自动管理所有TextField和scrollview。 You activate it with one line in AppDelegate so it's easy to use. 您可以在AppDelegate中用一行激活它,因此易于使用。

https://github.com/hackiftekhar/IQKeyboardManager https://github.com/hackiftekhar/IQKeyboardManager

Working but not as sleek as want it to be and also I was not capable to make IQKeyboardManager works so I did use inputAccessoryView . 工作,但不像想要的那样光滑,而且我也无法使IQKeyboardManager工作,所以我确实使用了inputAccessoryView

custom cell: 自定义单元:

import UIKit

protocol PortfolioCellDelegate {
    func portfolioButtonPressed(didSelect coinCell: PortfolioCell)
    func portfolioButtonPressed(coinCell:PortfolioCell, editingChangedInTextCell newValue:String)
}

class PortfolioCell: UITableViewCell, UITextFieldDelegate  {

    var delegate: PortfolioCellDelegate?

    ...

    @IBAction func editCellPressed(_ sender: UIButton) {
        textCell.becomeFirstResponder()
        delegate?.portfolioButtonPressed(didSelect: self)
    }

    @IBAction func textCellValueChanged(_ sender: UITextField) {

        if (sender.text?.isEmpty)! {
            delegate?.portfolioButtonPressed(coinCell: self, editingChangedInTextCell: "XXX")
        } else {
            let text = sender.text
            delegate?.portfolioButtonPressed(coinCell: self, editingChangedInTextCell: text!)
        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()

        self.textCell.delegate = self

        let flexiableSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
        let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(self.doneButtonAction))
        let toolBar:UIToolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: 35))

        toolBar.barTintColor = UIColor(red:0.15, green:0.69, blue:0.75, alpha:1.0)
        toolBar.tintColor = UIColor(red:0.93, green:0.93, blue:0.93, alpha:1.0)
        toolBar.setItems([flexiableSpace, doneButton], animated: false)

        textCell.inputAccessoryView = toolBar
        textCell.keyboardType = UIKeyboardType.decimalPad
    }

    @objc func doneButtonAction() {
        textCell.endEditing(true)
    }

    ...       
}

ViewController: ViewController:

import UIKit

class PortfolioViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, PortfolioCellDelegate {

    let getData = GetData()

    ...


    override func viewDidLoad() {
        super.viewDidLoad()        

        cellTableView.delegate = self
        cellTableView.dataSource = self

        cellTableView.register(UINib(nibName: "PortfolioCell", bundle: nil), forCellReuseIdentifier: "portfolioCell")

        self.currencyControl.selectedSegmentIndex = MyVariables.currencyControlSelected

        getData.delegate = self

        timeStampLabel.text = MyVariables.timeStamp
    }   

    override func viewDidAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.cellTableView.reloadData()
        self.currencyControl.selectedSegmentIndex = MyVariables.currencyControlSelected
        self.timeStampLabel.text = MyVariables.timeStamp
    }

    //MARK: - tableView
    /***************************************************************/

    ...


    func portfolioButtonPressed(coinCell: PortfolioCell, editingChangedInTextCell newValue: String) {
        let indexPath = self.cellTableView.indexPathForRow(at: coinCell.center)!
        let selectedCell = cellTableView.cellForRow(at: indexPath) as! PortfolioCell

        selectedCell.priceCell.isHidden = false
        selectedCell.textCell.isHidden = true

        if newValue != "XXX" {
            let owned: Double = Double(newValue)!
            MyVariables.dataArray[indexPath.row].ownedCell = owned
        }

        selectedCell.priceCell.isHidden = false
        selectedCell.textCell.isHidden = true

        self.cellTableView.reloadRows(at: [indexPath], with: .automatic)
    }

    func portfolioButtonPressed(didSelect coinCell: PortfolioCell) {
        let indexPath = self.cellTableView.indexPathForRow(at: coinCell.center)!
        let selectedCell = cellTableView.cellForRow(at: indexPath) as! PortfolioCell

        selectedCell.priceCell.isHidden = true
        selectedCell.textCell.isHidden = false
    }
        ...

} }

这很容易:您应该选择该表格视图单元,然后在属性检查器中启用“启用用户交互”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 单击按钮时 UITextField 不会结束编辑(委托 textFieldDidEndEditing ) - UITextField doesn't end editing when Button clicked( delegate textFieldDidEndEditing ) 禁用了用户交互的UITableViewCell和UITextField不会调用didSelectRow - UITableViewCell and UITextField with user interaction disabled doesn't call didSelectRow 使用 Swift 在 UITableViewCell 中获取 UITextField 的 indexPath - Get indexPath of UITextField in UITableViewCell with Swift UITextField:第一次编辑后键盘没有出现 - UITextField : Keyboard doesn't come up after first editing UIButton 不适用于自定义 UITableViewCell (Swift) - UIButton doesn't work on a custom UITableViewCell (Swift) UITableViewCell在Swift中不显示内容 - UITableViewCell doesn't show content in Swift 自定义 UITableViewCell 内容在编辑时不会移动 - Custom UITableViewCell content doesn't move when editing iOS 7:自定义UITableViewCell内容在编辑时不会移动吗? - iOS 7 : Custom UITableViewCell content doesn't move expected on editing? 在子类中实现 textRectForBounds 和编辑 RectForBounds 后 UITextField 不滚动到最后? - UITextField doesn't scroll to the end after implementing textRectForBounds and editingRectForBounds in a subclass? Swift 3:从自定义UITableViewCell中的UITextField检索文本 - Swift 3: retrieving text from a UITextField in a custom UITableViewCell
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM