簡體   English   中英

重新加載數據無限循環后,tableview選擇行

[英]tableview select row after reload data infinite loop

我有一個tableView在每個單元格中都有一個textField列表,並且使用UITextFieldDelegate。 用戶可以寫自己想要的內容並添加行。

問題在於必須重新加載tableview才能將結果顯示給用戶,但它破壞了beginFirstResponder()的功能。

我在self.tableView.reloadData()之后嘗試了這種解決方案:

1

let cell = self.tableView.dequeueReusableCell(withIdentifier: Cell.identifier, for: IndexPath(item: 0, section: 0)) as! Cell
textFieldDidBeginEditing(cell.textFiedl)

2

let cell = tableView(self.tableView, cellForRowAt: indexPath) as! CellItemOptions
cell.nameOptionsItem.becomeFirstResponder()

3

let cell = self.tableView.cellForRow(at: indexPath) as! CellItemOptions
cell.nameOptionsItem.becomeFirstResponder()

但這是行不通的。

謝謝您的幫助 !

編輯:我的代碼

import UIKit

class OptionsItemViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    var textFiedlDelegate: UITextField? = nil
    var categorySelected: Category?
    var options: [String] = []
    var nameOptions: [String] = []
    var cellSelected: Int = 0
    var viewHeight: CGFloat = 0
    var selectedRow: IndexPath? = nil
    var tableviewNeedToReload: Bool = false

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var keyboardAlwaysShow: UITextField!
    @IBOutlet weak var newFeatureButton: UIBarButtonItem!

    private let db = DataBase()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.tableView.dataSource = self
        self.textFiedlDelegate?.delegate = self
        self.title = categorySelected!.name
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        db.getItemOptions(predicateFormat: "id == \(self.categorySelected!.id)", completion: { results in
            self.categorySelected = results.first!
            self.options = self.categorySelected!.options as! [String]
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        })
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(false)
        self.viewHeight = self.view.frame.size.height
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(false)
        var index = 0
        while index < self.options.count {
            if self.options[index] != "" {
                index += 1
            } else {
                self.options.remove(at: index)
            }
            db.setCategoryOptions(category: self.categorySelected!, options: self.options, index: cellSelected)
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

    @IBAction func newFeature(_ sender: Any) {
        if self.options.last != "" {
            let indexPath: IndexPath = IndexPath(row: self.options.count, section: 0)
            self.options.append("")
            self.tableView.reloadData()

            let cell = tableView(self.tableView, cellForRowAt: indexPath) as! CellItemOptions
            cell.nameOptionsItem.becomeFirstResponder()
        }
    }

    // MARK: - TableView Functions

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let option = options[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: CellItemOptions.identifier, for: indexPath) as! CellItemOptions
        cell.nameOptionsItem.delegate = self
        cell.configureCell(with: option)
        return cell
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        self.cellSelected = options.index(of: textField.text!)!
        let indexPath: IndexPath = IndexPath(row: self.cellSelected, section: 0)
        self.tableView.reloadData()
        let cell = self.tableView.cellForRow(at: indexPath) as! CellItemOptions
        cell.nameOptionsItem.becomeFirstResponder()
    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField.text! == "" {
            if self.options[cellSelected] != "" {
                db.setRemoveDetailsItem(category: self.categorySelected!, index: cellSelected)
            }
            self.options.remove(at: cellSelected)
        } else {
            self.options[cellSelected] = "\(textField.text!)"
            db.setAddDetailsItem(category: self.categorySelected!, index: cellSelected)
        }
        db.setCategoryOptions(category: self.categorySelected!, options: self.options, index: cellSelected)
    }

    // MARK: - Keyboard

    func keyboardWillShow(_ notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            if self.view.frame.size.height == self.viewHeight {
                self.view.frame.size.height -= keyboardSize.height
            }
        }
    }

    func keyboardWillHide(_ notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            if self.view.frame.origin.y != self.viewHeight {
                self.view.frame.size.height += keyboardSize.height
            }
        }
    }
}

class CellItemOptions: UITableViewCell {
    static let identifier = "OptionsItemCell"

    @IBOutlet weak var nameOptionsItem: UITextField!

    private let tableView = OptionsItemViewController()

    func configureCell(with cell: String) {
        nameOptionsItem.text = cell
    }
}

使用此代碼的問題是內存使用量增加,而CPU的使用率大約為100%! 我認為我已經創建了一個無限的指令,但是我沒有找到...

謝謝 !

因此,首先,#3絕對是您想要的。 #1和#2都只能由表視圖調用以實際設置單元格。 您不應該直接給他們打電話。 #3向tableview詢問已經存在的單元格(如果該索引路徑可見),這就是您想要的。

#3的代碼本身看起來還不錯,所以問題可能出在其他地方,您可以發布重新加載時調用的其余代碼嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM