Мое приложение падает, когда вы пытаетесь удалить элемент, и оно не отображает все три поля предупреждения? - PullRequest
0 голосов
/ 21 ноября 2019

image

ОБНОВЛЕННЫЙ КОД xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - Получает ошибку, а затем, когда я запускаю, я получаю фатальную ошибку, не уверен, почему это происходит, но это обновленный код после парней. Пожалуйста, дайте мне знать xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

        import UIKit

let defaults = UserDefaults(suiteName: "com.Saving.Data")

struct Product: Codable {
    var title: String
    var price: String
    var salePrice: String
}

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    var items: [(item: String?, price: String?, salesPrice: String?)] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        getData()
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
        getData()
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(true)
        storeData()
    }
    override var prefersStatusBarHidden: Bool {
        return true
    }

    @IBAction func addButtonTapped(_ sender: Any) {
        let alert = UIAlertController(title: "Product Information", message: nil, preferredStyle: .alert)
            alert.addTextField { (itemTF) in
                itemTF.placeholder = "Item"
            }

            alert.addTextField { (textField) in
                textField.placeholder = "Price"
            }

            alert.addTextField { (textField) in
                textField.placeholder = "Sale Price"
            }

            let action = UIAlertAction(title: "Add", style: .default) { (_) in

                var product : (item: String, price: String, salesPrice: String) = ("","","")

                if let textField1 = alert.textFields?[0], let text = textField1.text {
                    print(text)
                    product.item = text

                }

                if let textField2 = alert.textFields?[1], let text = textField2.text {
                    print(text)
                     product.price = text

                }

                if let textField3 = alert.textFields?[2], let text = textField3.text {
                    print(text)
                    product.salesPrice = text

                }
                self.add(product)
            }

            alert.addAction(action)
            present(alert, animated: true)
            storeData()
        }

       func add(_ product: (item: String, price: String, salesPrice: String)) {
            let index = 0
            items.insert(product, at: index)

            let indexPath = IndexPath(row: index, section: 0)
            tableView.insertRows(at: [indexPath], with: .left)
            storeData()
        }


     func storeData() {

           if let data = try? PropertyListEncoder().encode(items) {
               defaults?.set(data, forKey: "savedData")
           }
       }

       func getData() {

           if let data = defaults?.data(forKey: "savedData") {
               items = try! PropertyListDecoder().decode([Product].self, from: data)
           }
       }



}

extension ViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

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

        let cell = UITableViewCell()
        let product = items[indexPath.row]
        cell.textLabel?.text = product.item
        print(product.price ?? "")
        print(product.salesPrice ?? "")

        cell.contentView.backgroundColor = UIColor(red:0.92, green:0.92, blue:0.92, alpha:1.0)
        cell.textLabel?.textColor = UIColor(red:0.13, green:0.13, blue:0.13, alpha:1.0)
        tableView.separatorColor = UIColor(red:0.92, green:0.92, blue:0.92, alpha:1.0)


        return cell
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        guard editingStyle == .delete else { return }
        items.remove(at: indexPath.row)
        tableView.reloadData()
        storeData()
    }
}

Ответы [ 2 ]

2 голосов
/ 21 ноября 2019

Чтобы показать всю информацию о продукте, такую ​​как название, цена, цена продажи, вы должны сделать Класс или Структура или Tuple . Необходимо подтвердить Кодируемый Протокол для сохранения в UserDefaults .

struct Product: Codable {
    var title: String
    var price: String
    var salePrice: String
}

Затем необходимо создать пользовательский UITableViewCell с несколькими (этовремя 3) UILabel с и с правильными AutoLayoutConstraints для отображения всей информации о Product .

Вот полный код

import UIKit

struct Product: Codable {
    var title: String
    var price: String
    var salePrice: String
}

let defaults = UserDefaults(suiteName: "savedData")

class ViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!

    var items = [Product]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addButtonPressed))

        tableView.delegate = self
        tableView.dataSource = self

        getData()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        getData()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        storeData()
    }

    @objc func addButtonPressed() {

        let alert = UIAlertController(title: "Product Information", message: nil, preferredStyle: .alert)

        alert.addTextField { (itemTF) in
            itemTF.placeholder = "Item"
        }

        alert.addTextField { (textField) in
            textField.placeholder = "Price"
        }

        alert.addTextField { (textField) in
            textField.placeholder = "Sale Price"
        }

        let addAction = UIAlertAction(title: "Add", style: .default) { (_) in

            let firstTextField = alert.textFields![0] as UITextField
            let secondTextField = alert.textFields![1] as UITextField
            let thirdTextField = alert.textFields![2] as UITextField

            let product = Product(title: firstTextField.text!, price: secondTextField.text!, salePrice: thirdTextField.text!)

            self.items.append(product)
            self.tableView.reloadData()
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

        alert.addAction(addAction)
        alert.addAction(cancelAction)
        present(alert, animated: true)
    }

    func add(_ product: Product) {
            let index = 0
            items.insert(product, at: index)

            let indexPath = IndexPath(row: index, section: 0)
            tableView.insertRows(at: [indexPath], with: .left)
            storeData()
        }



    func storeData() {

        if let data = try? PropertyListEncoder().encode(items) {
            defaults?.set(data, forKey: "savedData")
        }
    }

    func getData() {

        if let data = defaults?.data(forKey: "savedData") {
            items = try! PropertyListDecoder().decode([Product].self, from: data)
        }
    }
}

extension ViewController: UITableViewDataSource, UITableViewDelegate {

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

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

        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell
        cell.data = items[indexPath.row]
        return cell
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        guard editingStyle == .delete else { return }
        items.remove(at: indexPath.row)
        self.tableView.reloadData()
        storeData()
    }
}

class CustomCell: UITableViewCell {

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var priceLabel: UILabel!
    @IBOutlet weak var salePriceLabel: UILabel!

    var data: Product? {
        didSet {
            guard let data = data else {return}

            titleLabel.text = data.title
            priceLabel.text = data.price
            salePriceLabel.text = data.salePrice

        }
    }

    override func awakeFromNib() {
        super.awakeFromNib()
    }
}

1 голос
/ 21 ноября 2019

Вы можете добавить 3 текстовых поля в alertView.

код:

@IBAction func addButtonTapped(_ sender: Any) {

    let alert = UIAlertController(title: "Product Information", message: nil, preferredStyle: .alert)
    alert.addTextField { (itemTF) in
        itemTF.placeholder = "Item"
    }

    alert.addTextField { (textField) in
        textField.placeholder = "Price"
    }

    alert.addTextField { (textField) in
        textField.placeholder = "Sale Price"
    }

    let action = UIAlertAction(title: "Add", style: .default) { (_) in

        var product : (item: String, price: String, salesPrice: String) = ("","","")

        if let textField1 = alert.textFields?[0], let text = textField1.text  as? String {
            print(text)
            product.item = text

        }

        if let textField2 = alert.textFields?[1], let text = textField2.text  as? String {
            print(text)
             product.price = text

        }

        if let textField3 = alert.textFields?[2], let text = textField3.text as? String {
            print(text)
            product.salesPrice = text

        }

    }

      self.add(product)

    alert.addAction(action)
    present(alert, animated: true)
}


func add(_ product: (item: String, price: String, salesPrice: String)) {
    let index = 0
    items.insert(product, at: index)

    let indexPath = IndexPath(row: index, section: 0)
    tableView.insertRows(at: [indexPath], with: .left)
    storeData()
}


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

    let cell = UITableViewCell()
    let product = items[indexPath.row]
    cell.textLabel?.text = product.item
    print(product.price)
    print(product.salesPrice)

    cell.contentView.backgroundColor = UIColor(red:0.92, green:0.92, blue:0.92, alpha:1.0)
    cell.textLabel?.textColor = UIColor(red:0.13, green:0.13, blue:0.13, alpha:1.0)
    tableView.separatorColor = UIColor(red:0.13, green:0.13, blue:0.13, alpha:1.0)

    return cell
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...