进入tableView的多个条目

时间:2018-12-12 18:16:11

标签: swift xcode tableview

我在tableView中输入多个属性时遇到问题。它只是继续显示最后一个属性。糖尿病是唯一的一种,我可以在tableView中显示。 如何编辑代码,以便TableView显示全部4个?

我需要而不是全部四个。我在核心数据中创建了属性,并将尝试将其存储到SQLite中。但这不是我创建的第一个实体。当我尝试从核心数据访问另一个实体时,我需要其他的东西吗? 也许你可以帮我 谢谢百万,祝圣诞节快乐

// MARK: - Table view data source

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

}

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "GPDCell", for: indexPath)

    let item = itemArray2[indexPath.row]

    cell.textLabel?.text = item.name
    cell.textLabel?.text = item.age
    cell.textLabel?.text = item.bmi
    cell.textLabel?.text = item.diabetes 

    return cell

}

@IBAction func AddPatientData(_ sender: UIBarButtonItem) {

    var textField = UITextField()

    let alert = UIAlertController(title: "Add Patient Data", message: "", preferredStyle: .alert)
    let action = UIAlertAction(title: "Add Data", style: .default) { (action) in




        let newItem = ItemPatient(context: self.context)


        newItem.name = textField.text!
        newItem.age = textField.text!
        newItem.bmi = textField.text!
        [enter image description here][1]newItem.diabities = [enter image description here][1]textField.text!



        self.itemArray2.append(newItem)


        self.saveItems()

    }

    alert.addTextField { (alertTextField) in
        alertTextField.placeholder = "Add Patient Name"
        print(alertTextField)
        textField = alertTextField
    }

    alert.addTextField { (ageTextField) in
        ageTextField.placeholder = "Add Patients Age"
        print(ageTextField.text)
        textField = ageTextField

    }
    alert.addTextField { (bmiTextField) in
        bmiTextField.placeholder = "Add Patients BMI"
        print(bmiTextField.text)
        textField = bmiTextField


    }

    alert.addTextField { (diaTextField) in
        diaTextField.placeholder = "Diabieties"
        print(diaTextField.text)
        textField = diaTextField

    }

    alert.addAction(action)
    present(alert, animated: true, completion: nil)

}


    func saveItems (){

        do{
            try context.save()
        }catch{
            print ("Error saving context \(error)")
        }

        self.tableView.reloadData()

}

    func loaditems (with request:NSFetchRequest<ItemPatient> = ItemPatient.fetchRequest() ){

        do{
            itemArray2 = try context.fetch(request)
        }catch{
            print("Error fetching data \(error)")
        }

        tableView.reloadData()

2 个答案:

答案 0 :(得分:0)

问题很明显。

此代码是错误的:

cell.textLabel?.text = item.name
cell.textLabel?.text = item.age
cell.textLabel?.text = item.bmi
cell.textLabel?.text = item.diabetes

...,因为重新分配了.text属性,所以显然-它将包含最后一个值(cell.textLabel?.text = item.diabetes)。

您当前使用UITableViewCell,但必须创建一个Custom Cell,并添加4个标签,然后分别初始化每个人的text属性。

下面是完整的解决方案:

//
//  ViewController.swift
//  CustomTableViewCellDemo
//
//  Created by Pavel Palancica on 12/12/18.
//  Copyright © 2018 I Dev TV. All rights reserved.
//

import UIKit

struct PatientData {
    var name: String
    var age: String
    var bmi: String
    var diabetes: String
}

class PatientDataCell: UITableViewCell {
    var nameLabel: UILabel
    var ageLabel: UILabel
    var bmiLabel: UILabel
    var diabetesLabel: UILabel

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        var labelFrame = CGRect(x: 20, y: 10, width: UIScreen.main.bounds.size.width - 40, height: 30)
        nameLabel = UILabel(frame: labelFrame)

        labelFrame.origin = CGPoint(x: 20, y: labelFrame.origin.y + 40)
        ageLabel = UILabel(frame: labelFrame)

        labelFrame.origin = CGPoint(x: 20, y: labelFrame.origin.y + 40)
        bmiLabel = UILabel(frame: labelFrame)

        labelFrame.origin = CGPoint(x: 20, y: labelFrame.origin.y + 40)
        diabetesLabel = UILabel(frame: labelFrame)

        super.init(style: style, reuseIdentifier: reuseIdentifier)

        contentView.addSubview(nameLabel)
        contentView.addSubview(ageLabel)
        contentView.addSubview(bmiLabel)
        contentView.addSubview(diabetesLabel)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    private var array: [PatientData] = [
        PatientData(name: "Pavel", age: "28", bmi: "100", diabetes: "diabetes Abc"),
        PatientData(name: "Andrei", age: "31", bmi: "101", diabetes: "diabetes Cde"),
        PatientData(name: "Adelina", age: "19", bmi: "102", diabetes: "diabetes Efg")
    ]

    private lazy var tableView: UITableView = createTableView()

    func createTableView() -> UITableView {
        let tableViewOrigin = CGPoint(x: 0, y: 0)
        let tableViewSize = view.bounds.size
        let tableViewFrame = CGRect(origin: tableViewOrigin, size: tableViewSize)
        let tableView = UITableView(frame: tableViewFrame, style: .plain)
        return tableView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        view.addSubview(tableView)

        tableView.register(PatientDataCell.self, forCellReuseIdentifier: "PatientDataCell")
        tableView.dataSource = self
        tableView.delegate = self
    }

    // MARK: UITableViewDataSource Methods

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // return a cell of type UITableViewCell or another subclass
        let cell = tableView.dequeueReusableCell(withIdentifier: "PatientDataCell", for: indexPath) as! PatientDataCell

        let item = array[indexPath.row]
        cell.nameLabel.text = item.name
        cell.ageLabel.text = item.age
        cell.bmiLabel.text = item.bmi
        cell.diabetesLabel.text = item.diabetes

        return cell
    }

    // MARK: UITableViewDelegate Methods

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 170
    }
}

此外,如果要在Storyboard中创建自定义单元,请参考以下示例(但需要根据用例进行调整):

https://www.ralfebert.de/ios-examples/uikit/uitableviewcontroller/custom-cells/

请注意,我假设每个标签只有一行,如果希望在需要时将它们扩展到2-3行,则必须添加“自动布局”约束,并且代码会变得更加复杂,但是肯定可行。

答案 1 :(得分:0)

我假设您要在四个表格视图单元格中显示这四个itemArray2属性之一?

通过创建一个新的单元格,您将走在正确的轨道上,您只需要修改函数,以便它知道在此特定调用期间要创建的单元格。 我建议像这样更改cellForRowAt函数:

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

   let cell = tableView.dequeueReusableCell(withIdentifier: "GPDCell", for: indexPath)

   let item = itemArray2[indexPath.row]

   // This switch will change the contents of the cell based on the index path
   switch indexPath.row {
   case 0:
      cell.textLabel?.text = item.name
   case 1:
      cell.textLabel?.text = item.age
   case 2:
      cell.textLabel?.text = item.bmi
   default:
      cell.textLabel?.text = item.diabetes
   }

   return cell
}