У меня есть вопрос относительно запуска отдельного перехода и хранения пользовательских данных в каждом объекте tableView (Пациент). Информация, которую я добавляю, одинакова для каждого пациента. Но у меня проблема в том, что информация об одном пациенте по-прежнему видна и другим пациентам.
импорт UIKit импортировать RealmSwift
class PatienIDViewController: UITableViewController {
let realm = try! Realm()
var itemArray: Results<Item>?
override func viewDidLoad() {
super.viewDidLoad()
//// Nicht vergessen
loaditems()
// // Do any additional setup after loading the view.
}
//Mark - TableView Datasource Methods
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return itemArray?.count ?? 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoItemCell", for: indexPath)
if let item = itemArray?[indexPath.row] {
cell.textLabel?.text = item.title
// Ternary operator
// value = condition ?
cell.accessoryType = item.done ? .checkmark : .none
}else{
cell.textLabel?.text = "No Patients added"
}
return cell
}
//Mark - TableView - Delegate Methods
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath:
IndexPath) {
if let item = itemArray? [indexPath.row] {
do{
try realm.write {
item.done = !item.done
}
}catch{
print ("Error saving done Status, \(error)")
}
}
tableView.reloadData()
// print(itemArray[indexPath.row])
// Accessory
// context.delete(itemArray[indexPath.row])
// itemArray.remove(at: indexPath.row)
// itemArray[indexPath.row].done = !itemArray[indexPath.row].done
// save(item: Item)
tableView.deselectRow(at: indexPath, animated: true)
// Hier könnte man einen Button einfügen
}
@IBAction func AddButtonPressed(_ sender: UIBarButtonItem) {
var textField = UITextField()
let alert = UIAlertController(title: "Add New Patient", message: "", preferredStyle: .alert)
let action = UIAlertAction(title: "Add Patient", style: .default) { (action) in
// what will happen once the surgeon clicks the Add Patient Item
let newItem = Item()
newItem.title = textField.text!
// newItem.dateCreated = Date()
newItem.done = false
self.save(item: newItem)
}
alert.addTextField { (alertTextField) in
alertTextField.placeholder = "Add New Patient iD"
print(alertTextField.text!)
textField = alertTextField
}
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
func save (item: Item) {
do {
try realm.write {
realm.add(item)
}
}catch{
print ("Error saving context \(error)")
}
self.tableView.reloadData()
}
/// Read the Data
func loaditems() {
itemArray = realm.objects(Item.self)
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCell.EditingStyle.delete{
if let item = itemArray?[indexPath.row] {
try! realm.write {
realm.delete(item)
}
tableView.deleteRows(at: [indexPath], with: UITableView.RowAnimation.automatic)
}
}
}
}
Вопрос в том виде, в каком он сформулирован, несколько расплывчато сформулирован. Но я предполагаю, что у вас есть список Patient
, отображаемый в PatientListViewController
, и когда пользователь нажимает строку таблицы, вы хотите передать один Patient
в PatientDetailViewController
, и вы хотите сделать это, запустив переход.
Сначала реализуйте свой UITableViewDelegate:
extension PatientListViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let patient = patient(at: indexPath) // Implement this in your class
performSegue(withIdentifier: "toPatientDetail", sender: patient)
}
}
Затем отправьте отдельного пациента в контроллер представления:
class PatientListViewController: UIViewController {
// ...
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
let destinationPatient = sender as! Patient
let destination = segue.destination as! PatientDetailViewController
destination.patient = destinationPatient
}
// ...
}
Спасибо за помощь, я обновил свой вопрос и добавил код, в котором хочу реализовать решение.
@Jonas Я думаю, что вместо того, чтобы просто публиковать дополнительный код, вам нужно перефразировать свой вопрос, если мой ответ не соответствует ему, или, по крайней мере, принять мой ответ, если он действительно отвечает на него. В любом случае, также узнайте, как правильно форматировать код в StackOveflow - спасибо! :)
Я предлагаю обновить ваш вопрос с помощью кода, который вы используете для: а) заполнения таблицы, б) отображения нового контроллера при щелчке по ячейке, в) заполнения данных пациента в новый контроллер.