ios - 检测 UITableView HeaderView 中 UISegmentedControl 的变化

标签 ios swift uitableview uisegmentedcontrol uitableviewsectionheader

我正在尝试控制我的 UITableView基于 selectedSegmentIndexUISegmentedControl在我的 UITableView header 中。本质上,我想要这个 UISegmentedControl像 Twitter 的“我”选项卡一样工作。我有 UISegmentedControlUITableView 里面 header 并使用此方法将其出列:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let cell = tableView.dequeueReusableCell(withIdentifier: "sectionDetailsHeaderView") as! SectionDetailsHeaderTableViewCell
    return cell
}

我有一个连接到 SectionDetailsHeaderTableViewCell 的 UISegmentedControl socket ,但我不知道如何检测 UISegmentedControl 中的变化。我想设置一个变量,var segmentedControlValue = Int()selectedSegmentIndex每次值更改并调用函数时,func chooseDataToDisplay() {}当值改变时。我该怎么做?

最佳答案

借助@Schomes 的回答和this post ,我能够弄明白!

1) 将 UISegmentedControl 添加到它自己的 UITableViewCell 中。我建议在覆盖整个 UITableViewCellUISegmentedControl 后面添加一个带有白色背景的 UIView,以便 TableView 单元格在 UISegmentedControl 后面流动

2) 添加您的自定义单元格类并将其连接到 UITableViewCell

3) 添加一个 socket ,例如 yourSegmentedControl 到您的自定义 UITableViewCell 类。不要将操作添加到自定义 UITableViewCell 类中。这是在第 4 步中以编程方式完成的。

4) 在UIViewControllerUITableViewController 类中,添加以下代码。

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "yourCellIdentifier") as! yourCustomCellClass
    header.yourSegmentedControl.selectedSegmentIndex = self.segmentedControlValue
    header.yourSegmentedControl.addTarget(self, action: #selector(self.getSegmentValue(sender:)), for: .valueChanged)
    return header
}

self.segmentedControlValue 应在 ViewController 类的顶部声明为 var segmentedControlValue = Int()self.getSegmentValue(sender:) 应声明为:

func getSegmentValue(sender: UISegmentedControl) {
    self.segmentedControlValue = sender.selectedSegmentIndex
}

5) 你还需要添加:

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 45
}

这是标题的高度。在我的例子中,大小是 45

6) 您现在可以在 ViewController 中的任何位置访问 self.segmentedControlValue。当用户点击不同的片段时,它会更新。

关于ios - 检测 UITableView HeaderView 中 UISegmentedControl 的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41516751/

相关文章:

ios - 更新 CocoaPods 后找不到 header

ios - 在 iOS 7 中预加载数据库

objective-c - 无法识别的选择器 : [NSSQLToMany _setInverseManyToMany:]

iphone - 我为什么要做[对象释放];对象=零;什么时候释放一个对象?

mysql - 将模型对象链接到 Vapor 中的现有数据库表

swift - 可编码结构包含协议(protocol)属性

json - 使用按钮更新用户位置并快速绘制路线

ios - 通过点击 TableView 单元格将数据传递到详细 View

iphone - 如何以编程方式添加 UISearchDisplay Controller ?

ios - 类型 'UITableViewCell' 的值没有成员