Swift: Unsatisfying constraints (auto layout) after tableView reloadSections - swift

my problem looks like a weird behavior to me. I'm using Swift and iOS9+.
I've set up an UIViewController in storyboard with some views and a tableview. (Views are vertically above the tableview) All is set up properly with autolayout, no warnings and the UIViewController displays correctly.
In viewDidLoad() I request some table view data from an API and call tableView.reloadSections() after getting the response, the section fades correctly.
If I tap on a button in the section header, another view controller is presented where I can filter the requested data. After setting the filter, the view controller dismisses and the refreshVitalSigns(...) is called in the delegate.
Then again, I want to reload the table view section to only show the filtered data. When I call reloadSections() again, I get a lot of unsatisfying constraint warnings and the view is messed up, and I don't know why??????
With reloadData() everything works, but I only want to reload the section.
FYI: After requesting the API data, you have to scroll to see the whole table view content. If I scroll first, to see the whole content, and filter afterwards, also the reloadSections() works well! Obviously, it should also work without scrolling first...
Do you have any idea why this strange behavior happens?
I'm greatful for every hint!!!
Best
class JMProfileViewController: UIViewController {
/// Table view top spacing
#IBOutlet weak var tableViewTopSpacing: NSLayoutConstraint!
/// Table view
#IBOutlet var tableView: UITableView!
/// Attention view
#IBOutlet var attentionView: JMAttentionView?
var vitalSigns: [Items] = []
var data: [Items] = []
...
// View did load
override func viewDidLoad() {
super.viewDidLoad()
...
// Table view row height
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 44.0
// Register custom tableview header/footer views and cells
...
// Get table view data
let patientId = ...
getData(patientId)
}
/**
Get data
- parameter patientId: Patient ID
*/
func getData(patientId: Int) {
// Request
APIController.sharedInstance.getData(patientId: patientId) { response in
// Result handling
switch response {
case .Success(let result):
// Update vital signs
self.vitalSigns = result
self.data = result
// Reload data
self.tableView.beginUpdates()
self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: .Fade)
self.tableView.endUpdates()
case .Failure(let error):
print(error)
}
}
}
override func updateViewConstraints() {
super.updateViewConstraints()
// Set constraints depending on view's visibility
if let view = attentionView {
if view.hidden {
tableViewTopSpacing.constant = 0
} else {
tableViewTopSpacing.constant = view.bounds.height
}
}
}
// MARK: - Navigation
// Preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Data segue
if segue.identifier == SegueIdentifier.JMVitalSignsSegue.rawValue {
let vsvc = segue.destinationViewController as! JMVitalSignsViewController
vsvc.delegate = self
}
}
}
// MARK: - UITableViewDataSource
extension JMProfileViewController: UITableViewDataSource {
// Number of sections in table view
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3
}
// Height for header in section
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return section == 0 ? 0 : UITableViewAutomaticDimension
}
// Estimated height for header in section
func tableView(tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
return section == 0 ? 0 : 27.0
}
// View for header in section
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
switch section {
case 0:
// First section without header
return nil
case 1:
// Configure header
let header = tableView.dequeueReusableHeaderFooterViewWithIdentifier(CellIdentifier.JMTitleButtonHeaderView.rawValue) as! JMTitleButtonHeaderView
header.configure(NSLocalizedString("vitalSigns", comment: ""), buttonTarget: self, buttonImage: UIImage(named: "ic_filter_dark"), buttonAction: #selector(parameterButtonTapped(_:)))
return header
default:
// Configure header
let header = tableView.dequeueReusableHeaderFooterViewWithIdentifier(CellIdentifier.JMTitleButtonHeaderView.rawValue) as! JMTitleButtonHeaderView
header.configure(NSLocalizedString("others", comment: ""))
return header
}
}
/**
Vital signs button tapped
*/
func parameterButtonTapped(sender: UIButton) {
// Show vital signs view controller
self.performSegueWithIdentifier(SegueIdentifier.JMVitalSignsSegue.rawValue, sender: self)
}
// Number of rows in section
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rows = 0
switch section {
case 0:
// Diagnosis
rows = 1
break
case 1:
// Vital signs
rows = data.count > 0 ? data.count : 1
break
case 2:
// Others
rows = 3
break
default:
break
}
return rows
}
// Cell for row at indexpath
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier.JMSubtitleImageRightDetailCell.rawValue, forIndexPath: indexPath) as! JMSubtitleImageRightDetailCell
// Configure cell
...
return cell
case 1:
if data.count > 0 {
let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier.JMTitleThreeLabelsSubtitleCell.rawValue, forIndexPath: indexPath) as! JMTitleThreeLabelsSubtitleCell
// Configure cell
let item = data[indexPath.row]
cell.configure(item.caption, unit: item.unit, values: item.values)
cell.accessoryType = .DisclosureIndicator
return cell
} else {
let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier.JMBasicCell.rawValue, forIndexPath: indexPath)
// Configure cell
cell.textLabel?.text = NSLocalizedString("noData", comment: "")
cell.selectionStyle = .None
return cell
}
default:
let cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier.JMBasicCell.rawValue, forIndexPath: indexPath) as! JMDefaultCell
...
return cell
}
}
}
// MARK: - JMVitalSignsViewControllerDelegate
extension JMProfileViewController: JMVitalSignsViewControllerDelegate {
/**
Refresh vital signs
*/
func refreshVitalSigns(selectedItems: [Items]) {
print("Refresh vital signs")
var data: [Items] = []
for item in selectedItems {
for vitalItem in vitalSigns {
if item.match == vitalItem.match {
data.append(vitalItem)
break
}
}
}
self.data = data
// HERE IS MY PROBLEM
// tableView.beginUpdates()
// tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: .Fade)
// tableView.endUpdates()
tableView.reloadData()
}
}

Finally I've found a workaround.
I changed the UIViewController into a UITableViewController and added every custom UIView in the TableViewHeader (NOT Section header) with auto layout.
Now it works!

Related

Call the same view again so that another option can be selected in UITableViewController

Background:
Simple app that lets you select a currency from a UITableViewController, calls the same view again to make a second choice then takes user to a new view which displays the two selected currencies and exchange rate
So theoretically to me, this is only 2 views. The first being the currency list and the second is presenting chosen currencies/exchange rates. The first view is complete design wise. But I am struggling on how to make the connection between the first and second choice as it's calling the same view. How would I do this?
In my didSelectRowAt, I would typically performSegue but how do I call the same view and record the value selected from the first view? An idea I had was call a function that would record if an option is selected, and if so, call the new view else call the same view again but I'm not sure how I would implement this. Any help is appreciated!
My code thus far:
import UIKit
class SelectCurrencyTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
// Get the JSON data to insert into the table
func parseJSONData()-> Array<Any> {
var finalArray = [Any]()
if let url = Bundle.main.url(forResource: "currencies", withExtension: "json") {
do {
let data = try Data(contentsOf: url)
let jsonResult = try JSONSerialization.jsonObject(with: data)
if var jsonArray = jsonResult as? [String] {
while jsonArray.count > 0 {
let result: [String] = Array(jsonArray.prefix(2))
finalArray.append(result)
jsonArray.removeFirst(2)
}
}
} catch {
print(error)
}
}
return finalArray
}
func checkOptionsCount()-> Int{
// somehow check if option selected?
return 1
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return parseJSONData().count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCellController
if let array = parseJSONData()[indexPath.row] as? [String]{
cell.countryCodeLabel.text = array[0]
cell.currencyLabel.text = array[1]
cell.countryFlag.image = UIImage(named: array[0])
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// if this is 1st time, present view again
if (checkOptionsCount() == 1){
// if this is 2nd time, show new view
} else if (checkOptionsCount() == 2){
// performSegue with new view
} else {
print("How did I get here")
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
Seeing your code, I am assuming you are using storyboards. One way to accomplish what you want can be like this:
In Interface Builder select your SelectCurrencyTableViewController and add Storyboard ID to it:
Add a property where you will store your selected currency to SelectCurrencyTableViewController, something along these lines:
class SelectCurrencyTableViewController: UITableViewController {
var selectedCurrency: Currency?
//...
}
Then in didSelectRow:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// if this is 2nd time, show new view
if let selected = selectedCurrency {
// performSegue with new view
// if this is 1st time, present view again
// these is no selected currency passed from previous view controller, so this is the first time
} else {
//get view controller from storyboard using storyboard id (replace "Main" with your storyboard's name
let vc = UIStoryboard(name: "Main", bundle: nil)
.instantiateViewController(withIdentifier: "SelectCurrencyTableViewController") as! SelectCurrencyTableViewController
vc.selectedCurrency = //place code for getting first currency based on indexPath.row here
show(vc, sender: self)
}
}

Ho to create single tableview for two UISegment Control with two different selection check mark using Swift?

I am maintaining UISegmentControl and Search with a single tableview. Here, I am loading the tableview data from a JSON (language list).
Now I have two segment buttons like Source language and Target language and both segments tableviews also have same data. Here, whenever user selects source language a particular row is check marked and if then user clicks target language segment, the same check mark shows. I need to maintain separate data selections, also, I am going to use search bar.
Can you please provide me a solution for two different segment controller buttons but maintaining a single tableview and its data and UI look the same. Checkmark selection should be different and persistent.
My Code
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "languagecell", for: indexPath) as! LangCustomCell
let item = langData[indexPath.row]
cell.flag_img.sd_setImage(with:url, placeholderImage: UIImage(named: "usa.png"))
cell.language_label.text = item.languageName
cell.language_label.textColor = UIColor.gray
cell.selectionStyle = .none
//configure you cell here.
if(indexPath.row == selectedIndex) {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
return cell
}
Create two separate variables to store selected languages for from and to.
In tableView didSelectRowAt method check save in appropriate variable based on the selectedSegmentIndex. In TableView cellForRowAt check the selected languages with current language. If selectedSegmentIndex and selected language matches use .checkmark else use .none
And create two arrays with type [Language]. In searchBar textDidChange method filter the languages array and reload the tableView.
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
struct Language: Equatable {
var title: String
var icon: UIImage?
}
var allLanguages = [Language]()
var filteredLanguages = [Language]()
var selectedFromLanguage:Language?
var selectedToLanguage:Language?
let segmentedControl = UISegmentedControl()
let tableView = UITableView()
let searchBar = UISearchBar()
override func viewDidLoad() {
super.viewDidLoad()
allLanguages = [Language(title: "English", icon: UIImage(named:"uk"))]
filteredLanguages = allLanguages
// add constraints segmentedControl, tableView, searchBar in view
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredLanguages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") ?? UITableViewCell(style: .default, reuseIdentifier: "Cell")
cell.textLabel?.text = filteredLanguages[indexPath.row].title
cell.imageView?.image = filteredLanguages[indexPath.row].icon
if segmentedControl.selectedSegmentIndex == 0 && selectedFromLanguage == filteredLanguages[indexPath.row] {
cell.accessoryType = .checkmark
} else if segmentedControl.selectedSegmentIndex == 1 && selectedToLanguage == filteredLanguages[indexPath.row] {
cell.accessoryType = .checkmark
} else {
cell.accessoryType = .none
}
return cell
}
// MARK: - Table view Delegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if segmentedControl.selectedSegmentIndex == 0 {//from
selectedFromLanguage = filteredLanguages[indexPath.row]
} else {//to
selectedToLanguage = filteredLanguages[indexPath.row]
}
tableView.reloadData()
}
// MARK: - Search bar Delegate
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
if searchText.isEmpty {
filteredLanguages = allLanguages
} else {
filteredLanguages = allLanguages.filter({ $0.title.localizedCaseInsensitiveContains(searchText) })
}
tableView.reloadData()
}
}
Use computed properties like this to persist the selected languages
var selectedFromLanguage:Language? {
get {
if let data = UserDefaults.standard.value(forKey: "fromLanguage") as? Data,
let language = try? JSONDecoder().decode(Language.self, from: data) {
return language
}
return nil
}
set {
if let data = try? JSONEncoder().encode(newValue) {
UserDefaults.standard.set(data, forKey: "fromLanguage")
}
}
}
var selectedToLanguage:Language? {
get {
if let data = UserDefaults.standard.value(forKey: "toLanguage") as? Data,
let language = try? JSONDecoder().decode(Language.self, from: data) {
return language
}
return nil
}
set {
if let data = try? JSONEncoder().encode(newValue) {
UserDefaults.standard.set(data, forKey: "toLanguage")
}
}
}
setup an action for your UISegmentControl:
#IBAction func segmentChanged(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
// do what you need with your tableView
case 1:
// do what you need with your tableView
default:
return
}
}
when the index change setup your tableView and reload your data

toggle button with boolean in UITableView Swift

I would like to add a boolean toggle to know whether the button has been pressed (will save this value to core data (also would like to save cell data to core data if true and delete from core data if false)) I am not sure how to do this. any help would be greatly appreciated. if all the code from the view controller is required leave a comment and I will do so (I have setup xcdatamodel already).
#IBAction func buttonTapped(_ sender:UIButton) {
var superView = sender.superview
while !(superView is UITableViewCell) {
superView = superView?.superview
}
let cell = superView as! UITableViewCell
if let indexpath = tableView.indexPath(for: cell){
print(indexpath)
}
}
Well I build a simple project and I figured something out using protocols,
First you define a protocol like this:
protocol cellDidRequestSaving {
func saveOrDelete(indexpath : Int)
}
First in your cell you define you button like this :
class TableViewCell: UITableViewCell {
var delegate: cellDidRequestSaving?
var indexPath = 0 //come from the parent
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
#IBAction func didTap(_ sender: Any) {
// this protocol defined in the parent
delegate?.saveOrDelete(indexpath: indexPath)
}
}
now in you tableViewController you use the protocol like this:
class TableViewController: UITableViewController, cellDidRequestSaving {
var cellStat = [Int:Bool]()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 3
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
cell.indexPath = indexPath.row
cell.delegate = self
// Configure the cell...
return cell
}
func saveOrDelete(indexpath: Int) {
if let status = cellStat[indexpath], status {
print(indexpath, "delete")
cellStat[indexpath] = !status
}
else {
print(indexpath, "save")
cellStat[indexpath] = true
}
}
This is a simple project but you can get the hole idea about how to do it. Also, notice the protocol definition and usage so you wont miss anything.
and the out put is this
Add a property to your custom cell, for example:
var indexPath: IndexPath = IndexPath(row: -1, section: -1) //The -1 just know when it is not set yet
And in cellForRow in your tableView:
cell.indexpath = indexPath
Supposing that buttonTapped is defined in your custom cell class:
#IBAction func buttonTapped(_ sender:UIButton) {
print(indexpath)
}
Add a delegate method to your cell - (void)myCell:(MyCell *)cell didTapButton:(UIButton *)button
So then in your VC you can work backwards from the cell object.
- (void)myCell:(MyCell *)cell didTapButton:(UIButton *)button
{
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
MyObject *object = [self.dataSource objectAtIndexPath:indexPath];
// Do something with the knowledge that the button in the cell for the object was tapped...
// For example
object.tapped = YES;
[object.managedObjectContext save:NULL];
}
Just need to convert to swift ;)

Can't get indexPath of cell in header

I have created prototype custom header cell for a tableView with a button on it. I am trying to get the indexPath of the cell when the button is tapped, but I don't receive it. Any idea what I am doing wrong here?
protocol MediaHeaderCellDelegate: class {
func editPost(cell: MediaHeaderCell)
}
class MediaHeaderCell: UITableViewCell {
weak var delegate: MediaHeaderCellDelegate?
#IBAction func moreOptionsAction(_ sender: UIButton) {
delegate?.editPost(cell: self)
}
}
class NewsfeedTableViewController:UITableViewController, MediaHeaderCellDelegate {
func editPost(cell: MediaHeaderCell) {
guard let indexPath = tableView.indexPath(for: cell) else {
print("indexpath could not be given")
return}
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
let cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.mediaHeaderCell) as! MediaHeaderCell
cell.delegate = self
cell.media = media[section]
return cell
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: Storyboard.mediaCell, for: indexPath) as! MediaTableViewCell
cell.currentUser = currentUser
cell.media = media[indexPath.section]
cell.delegate = self
return cell
}
}
So this is actually all about learning what section a section header belongs to?? Here’s what I do. I have a header class:
class MyHeaderView : UITableViewHeaderFooterView {
var section = 0
}
I register it:
self.tableView.register(
MyHeaderView.self, forHeaderFooterViewReuseIdentifier: self.headerID)
I use and configure it:
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let h = tableView
.dequeueReusableHeaderFooterView(withIdentifier: self.headerID) as! MyHeaderView
// other stuff
h.section = section // *
return h
}
Now if the header view is tappable or contains a button or whatever, learning what section this is the header of is trivial.
Your immediate issue is that you are using a table cell as a section header view. That should not be done. Once you resolve that, your next task is to determine the table section from the header view whose button was tapped.
First, change your MediaHeaderCell to be a header view that extends UITableViewHeaderFooterView and update your protocol accordingly:
protocol MediaHeaderViewDelegate: class {
func editPost(view: MediaHeaderView)
}
class MediaHeaderView: UITableViewHeaderFooterView {
weak var delegate: MediaHeaderViewDelegate?
#IBAction func moreOptionsAction(_ sender: UIButton) {
delegate?.editPost(cell: self)
}
}
Then you need to register the header view in your view controller.
Then update your viewForHeaderInSection:
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: Storyboard.mediaHeaderView) as! MediaHeaderView
view.delegate = self
view.media = media[section]
view.tag = section
return view
}
And last, update your protocol method implementation:
func editPost(view: MediaHeaderView) {
let section = view.tag
// do something
}
There is one possible issue with this. If your table allows sections to be added or removed, then it is possible that a header view's tag could be wrong when the button is tapped.

Change UITableView section header when it's on top

I am using a custom header from Xib file for my table view using this code:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let result: Result = (self.responseData?.result![section])!
let headerCell = Bundle.main.loadNibNamed("HeaderViewTableViewCell", owner: self, options: nil)?.first as! HeaderViewTableViewCell
headerCell.sectionName.text = "Title"
if (section == 0) {
headerCell.sectionName.textColor = UIColor(red: 49/255.0, green: 149/255.0, blue: 213/255.0, alpha: 1)
}
return headerCell
}
Then I want to change the header sectionName when it is scrolled to top, I have tried this code
let topSection = self.mainTable .indexPathsForVisibleRows?.first?.section
let currentHeader : HeaderViewTableViewCell = self.mainTable .headerView(forSection: topSection!) as HeaderViewTableViewCell
currentHeader.sectionName.textColor = UIColor.red
But I get this error: Cannot convert value of type 'UITableViewHeaderFooterView?' to type 'HeaderViewTableViewCell' in coercion
Is there any way to cast the headerView to my custom type?
First of all I suggest you to use UITableViewHeaderFooterView for your header view. You can make a subclass and add custom code. For this example I will use an empty subclass:
class HeaderView: UITableViewHeaderFooterView {
override func prepareForReuse() {
super.prepareForReuse()
// set you default color (other properties) here.
// when scrolling fast the view gets reused and sometimes
// the view that's on top will suddenly appear on the bottom still with the previous values
textLabel?.textColor = .black
}
}
Register your header view (I am skipping all other unrelated code):
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(HeaderView.self, forHeaderFooterViewReuseIdentifier: "Header")
// If you have a nib file for your HeaderView then register nib instead
// Make sure in our nib file you set class name to HeaderView
// And the file name is also HeaderView.xib
// tableView.register(UINib.init(nibName: "HeaderView", bundle: nil) , forHeaderFooterViewReuseIdentifier: "Header")
}
Implement delegate methods:
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 44
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: "Header")
view?.textLabel?.text = "Hello"
return view
}
Create a method for updating headers:
// Iterates through section header views and
// checks for positions in relation to the tableview offset
func updateHeaders() {
var sectionHeaders: [Int: HeaderView?] = [:]
var i = 0
while i < numberOfSections {
sectionHeaders[i] = tableView.headerView(forSection: i) as? HeaderView
i += 1
}
let availableHeaders = sectionHeaders.flatMap { $0.value != nil ? $0 : nil }
for (index, header) in availableHeaders {
let rect = tableView.rectForHeader(inSection: index)
if rect.origin.y <= tableView.contentOffset.y + tableView.contentInset.top || index == 0 {
header!.textLabel?.textColor = .red
} else {
header!.textLabel?.textColor = .black
}
}
}
And call your updateHeaders() from UIScrollViewDelegate method scrollViewDidScroll:
func scrollViewDidScroll(_ scrollView: UIScrollView) {
updateHeaders()
}
Also update headers before the view will be displayed (before any scroll appeared), for that use the UITableViewDelegate method willDisplayHeaderView:
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
updateHeaders()
}