ios - 在不使用额外单元格的情况下展开 TableViewCell

标签 ios swift uitableview uipickerview custom-cell

我正在使用带有自定义单元格的 UITableView。每个单元都有自己的 nib 文件和一个 Controller 。在一个单元格中,我想让用户选择一个日期。默认日期显示在单元格上。当用户点击单元格时,UIPickerView 应该在单元格上展开。我在论坛上发现了多个类似的问题,但它们都使用了一个包含 UIPickerView 的额外单元格。在我的应用程序中,我需要使用一个包含标签和 Pickerview 的 nib 文件。也许当单击单元格时,我应该显示 pickerView 并更新单元格高度,当再次单击单元格时,我应该隐藏它并再次更新高度。我在某处看到了一个示例,但它是用 Objective-C 编写的。您认为可以通过这种方式实现吗?是否有 Swift 示例?

最佳答案

好吧,要解决这个问题,您只需在单元格 View 中设置标签和选择器之间的固定垂直间距。看这个截图

fixed vertical spacing

然后每次用户点击单元格时,您只需重新加载表格 View ,并更新单元格的高度。这是源代码:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var tableView: UITableView!

fileprivate var cellExpanded = false

// MARK: - UITableView datasource & delegate

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "PickerCell")!

    return cell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return (cellExpanded) ? 260:44
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    cellExpanded = !cellExpanded
    tableView.reloadData()
}
}

关于ios - 在不使用额外单元格的情况下展开 TableViewCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42396441/

相关文章:

ios - Swift - 'NSArray' 不是 'inout C' 类型

ios - 在 TableView 中突出显示搜索字母 - ios

swift - 带有 Tableview 的自定义 Xib 单元格不起作用

ios - Nativescript IOS : Textview not resizing after Input was cleared

objective-c - 在 numberOfRowsInSection 中调用 TableView BeginUpdates

ios - 通过最后一个项目以编程方式将新项目添加到 CollectionView

swift - "Variadic enum cases are not supported"swift 5 错误

ios - Reusable Cell 没有调用 prepareForReuse 函数

ios - UICollectionView:重新排序不同但固定宽度的单元格

ios - 将 View Controller 关闭到上一个 View Controller