首页 > 解决方案 > 如何使用在 Swift 中具有展开折叠功能的自动布局创建 UI?

问题描述

我有一个 UI 要设计

此 UI 将没有展开

此 UI 将在展开之后

我需要UI使用它来创建它AutoLayout,我很困惑我应该只使用它UITableViewCell来创建这个 UI 还是我必须使用“Section. 另外,我将如何处理扩展崩溃可以有人帮助我。在此先感谢。

标签: uitableviewswift3uitableviewautomaticdimension

解决方案


您可以通过两种方式实现此目的首先创建2个原型单元格,一个用于标题视图,另一个用于详细信息视图,第二viewForHeaderInSection个原型单元格用于详细信息视图,并为每个部分创建标题。

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

所以你很容易处理第一个是代码。

import UIKit

public struct Section {
    var name: String
    var collapsed: Bool

    public init(name: String, collapsed: Bool = false) {
        self.name = name
        self.collapsed = collapsed
    }
}

class TableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!
    var sampleData: [Section] = [Section(name: "Header 1"),Section(name: "Header 2"),Section(name: "Header 3")]

设置数据后展开折叠uitableviewcell

//
// MARK: - View Controller DataSource and Delegate
//
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return sampleData[section].collapsed ? 2 : 1
}

func numberOfSections(in tableView: UITableView) -> Int {
    return sampleData.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // Header
    if indexPath.row == 0 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "header")!
        return cell
    }
    // Cell
    let cell = tableView.dequeueReusableCell(withIdentifier: "detailed")!
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if indexPath.row == 0 {
        let collapsed = !sampleData[indexPath.section].collapsed

        // Toggle collapse
        sampleData[indexPath.section].collapsed = collapsed
        self.tableView.reloadSections([indexPath.section], with: .automatic)
    }
}

在此处输入图像描述


推荐阅读