Así que tengo 2 Vistas que se muestran dentro de una UIView, en función de lo que se selecciona en el SegmentViewController. Creo datos ficticios, devolviendo 20 filas de una celda personalizada. Esto funciona muy bien.
Todo está bien, hasta que interactúo con TableView.
Abajo está mi código:
GoalsViewController.swift
import UIKit
class GoalsViewController: UIViewController {
@IBOutlet weak var goalsTableView: UITableView!
let goalCellIdentifier = "goalCell"
override func viewDidLoad() {
super.viewDidLoad()
goalsTableView.delegate = self
goalsTableView.dataSource = self
goalsTableView.register(UINib(nibName: "GoalsViewCell", bundle: nil), forCellReuseIdentifier: goalCellIdentifier)
goalsTableView.reloadData()
}
}
extension GoalsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = goalsTableView.dequeueReusableCell(withIdentifier: goalCellIdentifier, for: indexPath) as! GoalsViewCell
cell.goalTitle.text = "aaaaa"
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Selected \(indexPath.row)")
}
}
Después de seleccionar cualquiera de las filas vacías, no se llama a didSelectRowAt
, por lo que las celdas ya no están allí. Traté de encontrar una solución, pero solo tenía que encontrar problemas sobre listas vacías, antes de que se completaran.
¿Cuál podría ser el motivo de la vista de tabla vacía?
2 respuestas
Explicaré cuál era el problema para las personas que probablemente no sabían (como yo). Entonces mi UITableView
está dentro de un UIView
que cambia según lo que el usuario está seleccionando. En total, tuve 2 vistas diferentes que estaban cambiando. La razón por la que se estaba vaciando era porque mi ViewController principal no podía acceder al delegado para UITableView. Para solucionarlo, después de agregar una subvista a la UIView, también debe mover el ViewController al controlador principal. En código va así.
// Empty array of UIViewControllers
var views: [UIViewController]!
// Add the UIViewControllers to the array
views = [UIViewController()]
views.append(EventsViewController())
views.append(GoalsViewController())
for view in views {
// Needed to adjust the size of Subview to size of View
view.view.frame = containerView.bounds
// Add the subviews
containerView.addSubview(view.view)
}
// Bring the view in position 1 to the front of the UIView
containerView.bringSubviewToFront(views[1].view)
// Add Views[1] UIViewController as a child to the parent controller
self.addChild(views[1])
views[1].didMove(toParent: self)
// After done with everything with the UIViewController remove it
views[1].removeFromParent()
Podría estar equivocado aquí, pero una cosa que he notado es que no está implementando una función que establece la altura de cada celda.
// Specify the height of your cells
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100 // Or your given cell height.
}
Así que aquí está mi teoría: si está usando restricciones, falta algo y la altura de su celda no puede identificarse solo por restricciones o no está usando restricciones, por lo tanto, debe usar heightForRowAt para especificar la altura de cada celda.
Preguntas relacionadas
Nuevas preguntas
ios
iOS es el sistema operativo móvil que se ejecuta en el iPhone, iPod touch y iPad de Apple. Use esta etiqueta [ios] para preguntas relacionadas con la programación en la plataforma iOS. Use las etiquetas relacionadas [Objective-C] y [Swift] para problemas específicos de esos lenguajes de programación.