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
UISegmentedControl
into its ownUITableViewCell
. I would recommend adding aUIView
with a white background behind theUISegmentedControl
that covers the entireUITableViewCell
so the TableView cells flow behind theUISegmentedControl
.2) Add your custom cell class and hook it up to the
UITableViewCell
3) Add an outlet, such as
yourSegmentedControl
to your customUITableViewCell
class. DO NOT add an action into the customUITableViewCell
class. This is done programmatically in step 4.4) In the
UIViewController
orUITableViewController
class, add the code below.self.segmentedControlValue
should be declared asvar segmentedControlValue = Int()
at the top of yourViewController
class.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.segmentedControlValue
anywhere in yourViewController
. It will update when the user taps on a different segment.