I am trying to control my UITableView based on the selectedSegmentIndex of a UISegmentedControl inside my UITableView header. Essentially, I want this UISegmentedControl to work like Twitter's 'Me' tab. I have the UISegmentedControl inside a UITableView header and it is dequeued using this method:
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cell = tableView.dequeueReusableCell(withIdentifier: "sectionDetailsHeaderView") as! SectionDetailsHeaderTableViewCell
return cell
}
I have an outlet for the UISegmentedControl hooked up to SectionDetailsHeaderTableViewCell, but I can't figure out how to detect a change in the UISegmentedControl. I want to set a variable, var segmentedControlValue = Int() to the selectedSegmentIndex every time the value changes and call a function, func chooseDataToDisplay() {} when the value changes. How do I go about doing this?
With the help of @Schomes answer and this post, I was able to figure it out!
1) Add the
UISegmentedControlinto its ownUITableViewCell. I would recommend adding aUIViewwith a white background behind theUISegmentedControlthat covers the entireUITableViewCellso the TableView cells flow behind theUISegmentedControl.2) Add your custom cell class and hook it up to the
UITableViewCell3) Add an outlet, such as
yourSegmentedControlto your customUITableViewCellclass. DO NOT add an action into the customUITableViewCellclass. This is done programmatically in step 4.4) In the
UIViewControllerorUITableViewControllerclass, add the code below.self.segmentedControlValueshould be declared asvar segmentedControlValue = Int()at the top of yourViewControllerclass.self.getSegmentValue(sender:)should be declared as:5) You also need to add:
This is the height of the header. In my case, the size is 45
6) You can now access
self.segmentedControlValueanywhere in yourViewController. It will update when the user taps on a different segment.