簡體   English   中英

iOS開發Swift自定義單元

[英]iOS development Swift Custom Cells

我正在使用Swift開發應用程序,而“自定義單元格”存在問題。 我有一個自定義單元格,當您單擊“添加”按鈕時,它會創建另一個自定義單元格。 單元格具有3個文本字段和2個按鈕。 這些文本字段是名稱,價格和我正在創建的餐食成分的數量。 當我僅使用一個自定義單元格或添加一個自定義單元格使其成為兩個時,數據將正確存儲。 但是,當我添加2個自定義單元格(總共3個自定義單元格)時,我遇到了價格錯誤的問題,價格中僅計算了最后兩個成分。 當我添加3個自定義單元格(總共4個自定義單元格)時,它僅使用填充的數據(如第一個單元格)重新創建第一個單元格。 點擊完成按鈕時,出現一個致命錯誤:解開Optional值時發現nil。

查看控制器

import UIKit
import CoreData

class AddMealViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {

    @IBOutlet weak var mealNameTF: UITextField!

    @IBOutlet weak var addMealsCell: UITableViewCell!
    @IBOutlet weak var finishButton: UIButton!
    @IBOutlet weak var resetButton: UIButton!
    @IBOutlet weak var addButton: UIButton!
    @IBOutlet weak var addMealTableView: UITableView!

    @IBOutlet weak var productPrice: UILabel!
    let currency = "$" // this should be determined from settings
    var priceTotal = "0"

    override func viewDidLoad() {
        super.viewDidLoad()
        addMealTableView.delegate = self
        addMealTableView.dataSource = self
        borderToTextfield(textField: mealNameTF)
        mealNameTF.delegate = self
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            self.view.endEditing(true)
            return true;
        }

    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return counter
    }

    var counter = 1

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier:
            "addMealsCell", for: indexPath) as! AddMealsTableViewCell

        borderToTextfield(textField: (cell.amountTF)!)
        borderToTextfield(textField: (cell.ingredientNameTF)!)
        //borderToTextfield(textField: cell.normativeTF)
        borderToTextfield(textField: (cell.priceTF)!)



        return cell

    }


    @IBAction func addButton(_ sender: UIButton) {
        counter += 1

        addMealTableView.register(AddMealsTableViewCell.self, forCellReuseIdentifier: "addMealsCell")
        addMealTableView.reloadData()

    }



    @IBAction func resetButton(_ sender: UIButton) {
       mealNameTF.text = ""
        for c in 0..<counter{
            let indexPath = IndexPath(row: c, section:0)
            let cell = addMealTableView.cellForRow(at: indexPath) as! AddMealsTableViewCell
            cell.amountTF.text = ""
            cell.ingredientNameTF.text = ""
          //  cell.normativeTF.text = ""
            cell.priceTF.text = ""
        }
        productPrice.text = "\(currency)0.00"
        priceTotal = "0"
        counter = 1
    }

    @IBAction func finishButton(_ sender: UIButton) {
        for c in (0..<counter){
            if let cell = addMealTableView.cellForRow(at: IndexPath(row: c, section: 0)) as? AddMealsTableViewCell {
                cell.amountTF.delegate = self
                cell.ingredientNameTF.delegate = self
                // cell.normativeTF.delegate = self
                cell.priceTF.delegate = self

                guard cell.priceTF.text?.isEmpty == false && cell.amountTF.text?.isEmpty == false && mealNameTF.text?.isEmpty == false && cell.ingredientNameTF.text?.isEmpty == false
                    else {
                        return
                }

                if cell.priceTF.text?.isEmpty == false{
                //    if (true) {
                    let tfp = Double((cell.priceTF.text!))!*Double((cell.amountTF.text!))!
                    var ttp = Double(priceTotal)
                    ttp! += tfp
                    priceTotal = String(ttp!)
              //  }
                    }}
            }


        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext
        let newMeal = NSEntityDescription.insertNewObject(forEntityName: "Meal", into: context)
        let mealName = mealNameTF.text
        newMeal.setValue(mealName, forKey: "name")
        newMeal.setValue(priceTotal, forKey: "price")
        do {
            try context.save()

            print("Spremljeno")
        } catch  {
            print("Neki error")
        }

        productPrice.text = currency + priceTotal
    }

    @IBAction func addNewIngredientButton(_ sender: UIButton) {


    }
    func borderToTextfield(textField: UITextField){
        let border = CALayer()
        let width = CGFloat(2.0)
        border.borderColor = UIColor.white.cgColor
        border.frame = CGRect(x: 0, y: textField.frame.size.height - width, width:  textField.frame.size.width, height: textField.frame.size.height)

        border.borderWidth = width
        textField.layer.addSublayer(border)
        textField.layer.masksToBounds = true
        textField.tintColor = UIColor.white
        textField.textColor = UIColor.white
        textField.textAlignment = .center

    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.view.endEditing(true)
        return true;
    }
}

細胞

class AddMealsTableViewCell: UITableViewCell, UITextFieldDelegate{

    @IBOutlet weak var DropMenuButton: DropMenuButton!
    @IBOutlet weak var addNewIngredient: UIButton!
    @IBOutlet weak var ingredientNameTF: UITextField!

   // @IBOutlet weak var normativeTF: UITextField!

    @IBOutlet weak var amountTF: UITextField!

    @IBOutlet weak var priceTF: UITextField!

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        self.endEditing(true)
        return true;
    }

    override func prepareForReuse() {
        self.amountTF.text = ""
        self.priceTF.text = ""
        self.ingredientNameTF.text = ""
    }

    @IBAction func DropMenuButton(_ sender: DropMenuButton) {
        DropMenuButton.initMenu(["kg", "litre", "1/pcs"], actions: [({ () -> (Void) in
            print("kg")
            sender.titleLabel?.text = "kg"
        }), ({ () -> (Void) in
            print("litre")

            sender.titleLabel?.text = "litre"
        }), ({ () -> (Void) in
            print("1/pcs")
            sender.titleLabel?.text = "1/pcs"
        })])
    }

    @IBAction func addNewIngredient(_ sender: UIButton) {


        let name = ingredientNameTF.text
        let amount = amountTF.text
        let price = priceTF.text
        //  let normative = normativeTF.text

        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext
        let newIngredient = NSEntityDescription.insertNewObject(forEntityName: "Ingredient", into: context)

       newIngredient.setValue(name, forKey: "name")
       // newIngredient.setValue(normative, forKey: "normative")
       newIngredient.setValue(amount, forKey: "amount")
       newIngredient.setValue(price, forKey: "price")

        do {

            try context.save()
            print("Spremljeno")
        } catch  {
            print("Neki error")
        }
    }
}

您的代碼很難閱讀,但是我懷疑問題可能在這里:

func numberOfSections(in tableView: UITableView) -> Int {
    return counter
}

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

您將為各節和各節返回相同數量的行。 因此,如果您有1種成分,您說的是1節1行。 但是,如果您有2種成分,則是說有2個部分,每個部分有2個單元格(總共4個單元格)。

您的代碼還有很多其他要解決的問題,以下是一些:

最大的事情是,使用您擁有的counter變量會使您非常困難。 相反,如果您有各種各樣的成分

var ingredients = [Ingredient]()

您可以使用它來設置表格計數的所有內容。 像這樣:

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier:
        "addMealsCell", for: indexPath) as! AddMealsTableViewCell

    let ingredient = ingredients[indexPath.row]

    cell.ingredientNameTF.text = ingredient.name
    cell.normativeTF.text = ingredient.normative
    cell.amountTF.text = ingredient.amount
    cell.priceTF.text = ingredient.price

    return cell
}

所有這些都可以在界面構建器中設置(您不需要在視圖中為它們加載了代碼行):

    addMealTableView.delegate = self
    addMealTableView.dataSource = self
    mealNameTF.delegate = self

這行應該在您的viewDidLoad函數中,您只需要注冊一次該類,就在每次按下add時都在執行此操作。

addMealTableView.register(AddMealsTableViewCell.self, forCellReuseIdentifier: "addMealsCell")

您的動作名稱應該是動作

 @IBAction func addButtonPressed(_ sender: UIButton)
 @IBAction func resetButtonPressed(_ sender: UIButton)
 @IBAction func finishButtonPressed(_ sender: UIButton)

謝謝。 現在,當ViewController加載時,我沒有任何單元格。 我的數組現在為空,因此我必須對addButton實現一些代碼,該代碼創建另一個單元並重新加載tableView。 我怎樣才能做到這一點?

您只需要向配料數組添加一個新的配料對象,然后重新加載表格視圖的數據即可。

@IBAction func addButtonPressed(_ sender: UIButton) {
    let newIngredient = Ingredient()
    ingredients.append(newIngredient)
    tableView.reloadData()
}

暫無
暫無

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

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