syedfa syedfa - 1 year ago 79
Swift Question

Trying to set text of UILabel inside UIView of section header in UITableView using Swift

Dear fellow iOS developers:

I have a UITableView which I'm adding sections to. I have created a separate class which is a subclass of UITableHeaderFooterView. Here is the code for it:

import UIKit

class SectionHeader: UITableViewHeaderFooterView {

@IBOutlet weak var sectionHeaderLabel: UILabel!
@IBOutlet weak var sectionHeaderButton: UIButton!

@IBAction func showHideViewAction(sender: UIButton) {



What I'm trying to do is set the UILabel property that is contained in this class, inside the ViewController which contains my UITableView. In my viewDidLoad method for that class, I register the nib as follows:

let nib = UINib(nibName: "SectionHeaderView", bundle: nil)
self.addTravellerTableView.registerNib(nib, forHeaderFooterViewReuseIdentifier: "SectionHeaderView")

I am now trying to set the text of the UILabel property inside the following method:

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

if section == 1 {
let headerView = self.addTravellerTableView.dequeueReusableHeaderFooterViewWithIdentifier("SectionHeaderView")
//headerView.sectionHeaderLabel doesn't work.
return headerView
} else if section == 2{
return nil
} else {
return nil

I am unable to call the UILabel property, sectionHeaderLabel. When stepping through the code, "headerView" at least is coming across as an object of type of UIView.

Can anyone see what it is I'm doing wrong?

Thanks in advance to all who reply.

Answer Source

You need to tell the compiler the specific type of class that the function call will return so you need to add as! SectionHeader to the end of the line where you dequeue the view.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download