Sobes.tech
Junior — Middle

¿En qué se diferencian los componentes StackView y TableView en el desarrollo de interfaces?

sobes.tech AI

Respuesta de la IA

StackView y TableView son componentes diferentes para construir interfaces en iOS, que sirven a diferentes propósitos:

  • UIStackView es un contenedor para organizar vistas hijas en dirección horizontal o vertical. Gestiona automáticamente la disposición y tamaño de los elementos anidados, simplificando la creación de interfaces adaptativas sin necesidad de escribir mucho código para constraints.

  • UITableView es un componente para mostrar una gran lista de datos homogéneos en forma de tabla, con capacidad de reutilización de celdas, desplazamiento y actualización dinámica. Requiere implementar datasource y delegate para gestionar el contenido y comportamiento.

Ejemplo de uso de UIStackView:

let stackView = UIStackView(arrangedSubviews: [view1, view2, view3])
stackView.axis = .vertical
stackView.spacing = 10
stackView.distribution = .fillEqually
view.addSubview(stackView)
// Añadir constraints para stackView

Ejemplo básico de UITableView:

class MyViewController: UIViewController, UITableViewDataSource {
    let tableView = UITableView()
    let data = ["Item 1", "Item 2", "Item 3"]

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        view.addSubview(tableView)
        // Añadir constraints para tableView
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") ?? UITableViewCell(style: .default, reuseIdentifier: "cell")
        cell.textLabel?.text = data[indexPath.row]
        return cell
    }
}

Por lo tanto, StackView es para organizar elementos, TableView para mostrar listas de datos.