xcode tableView中的多个条目

x8diyxa7  于 2022-12-27  发布在  其他
关注(0)|答案(2)|浏览(88)

我在向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()
axkjgtzd

axkjgtzd1#

我假设您正尝试在四个表视图单元格中显示这四个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
}
eoigrqb6

eoigrqb62#

问题是显而易见的。
此代码错误:

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行,您必须添加自动布局约束,代码会变得有点复杂,但绝对可行。

相关问题