我正在尝试控制我的 UITableView
基于 selectedSegmentIndex
的 UISegmentedControl
在我的 UITableView header 中。本质上,我想要这个 UISegmentedControl
像 Twitter 的“我”选项卡一样工作。我有 UISegmentedControl
在 UITableView
里面 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
中。我建议在覆盖整个 UITableViewCell
的 UISegmentedControl
后面添加一个带有白色背景的 UIView
,以便 TableView 单元格在 UISegmentedControl 后面流动
。
2) 添加您的自定义单元格类并将其连接到 UITableViewCell
3) 添加一个 socket ,例如 yourSegmentedControl
到您的自定义 UITableViewCell
类。不要将操作添加到自定义 UITableViewCell
类中。这是在第 4 步中以编程方式完成的。
4) 在UIViewController
或UITableViewController
类中,添加以下代码。
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/