Swift - редактировать табличное представление после того, как вы вручную в него ввели данные - PullRequest
0 голосов
/ 27 февраля 2020

Я пытаюсь создать список задач с установкой / снятием отметки при выборе элемента.

У меня есть представление таблицы, в которое я хочу, чтобы пользователь мог вводить элементы в таблицу и увеличивать ее как требуется новый предмет.

Я могу ввести данные в список, и таблица увеличивается по мере ввода данных.

Но если мне нужно повторно ввести запись в список (т.е. исправить орфографическую ошибку), когда я выбираю ячейку, которую я хочу исправить, я получаю новую ячейку в таблице, где я ее не хочу и исправленный текст, который я ввожу, добавляется в мой массив вместо того, чтобы вводить текст в позиции списка, в которой он находился в списке.

Пожалуйста, помогите этому нубу ie.

Вот мой код :

ListTableViewControler

import UIKit
import os.log

class ListTableViewController: UITableViewController {

    //MARK: Properties
    var listText: [String] = [""]
    var ip: IndexPath = []
    var currentRow = Int()
    override func viewDidLoad() {
        super.viewDidLoad()
        // 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.leftBarButtonItem = self.editButtonItem

    }
    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1

    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return listText.count

    }

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

        // Configure the cell...
        let cellIdentifier = "ListTableViewCell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! ListTableViewCell

        return cell
    }
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

        // test to see if the index is empty if it is empty then disable the delete button.

        if editingStyle == .delete {
            // Delete the row from the data source
            listText.remove(at: currentRow)
            tableView.deleteRows(at: [IndexPath(row: currentRow, section: 0)], with: .automatic)
            tableView.reloadData()

        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }else {
            // disable Delete button if this is the last cell
            self.editButtonItem.isEnabled = false
        }

    }

    //MARK: Action

    @IBAction func update_Table(_ sender: UITextField) {
        let appendIndexPath = IndexPath(row: listText.endIndex, section: 0)
        //update table
        tableView.beginUpdates()
        listText[listText.count - 1] = sender.text!
        listText.append("")
        tableView.insertRows(at: [appendIndexPath], with: .automatic)
        tableView.endUpdates()
    }
}

ListViewCell

class ListTableViewCell: UITableViewCell, UITextFieldDelegate {

    @IBOutlet weak var checkMark: UIButton!
    @IBOutlet weak var itemText: UITextField!


    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        itemText.delegate = self
        checkMark.isSelected = false
        itemText.becomeFirstResponder()

    }

    //Mark: UITextfieldDelegate

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        //Hide Keyboard
        itemText.resignFirstResponder()
        return true
    }

    // reads the texts field data
    func textFieldDidEndEditing(_ textField: UITextField) {
        itemText.text = textField.text

    }

    //Mark: Action

    @IBAction func itemChecked(_ sender: UIButton) {
        // define button appearance for each state

        checkMark.setImage(UIImage.checkmark, for: UIControl.State.selected)
        let attributedString = NSMutableAttributedString(string: itemText.text!)
        //check button doesn't response if the text field  is empty
        if itemText.text?.isEmpty == false {
            // Change the state of the button and change the appearance of the check box
            if checkMark.isSelected == false {
                checkMark.isSelected = true
                attributedString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributedString.length))
                itemText.attributedText = attributedString

            }else{
                checkMark.isSelected = false
                attributedString.removeAttribute(NSAttributedString.Key.strikethroughStyle, range: NSMakeRange(0, attributedString.length))
                itemText.attributedText = attributedString
            }
        }
    }

}
...