Customize Uitableview Header Section

Swift - how to make custom header for UITableView?

Did you set the section header height in the viewDidLoad?

self.tableView.sectionHeaderHeight = 70

Plus you should replace

self.view.addSubview(view)

by

view.addSubview(label)

Finally you have to check your frames

let view = UIView(frame: CGRect.zeroRect)

and eventually the desired text color as it seems to be currently white on white.

Customize UITableView header section

You can try this:

 -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 18)];
/* Create custom view to display section header... */
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, tableView.frame.size.width, 18)];
[label setFont:[UIFont boldSystemFontOfSize:12]];
NSString *string =[list objectAtIndex:section];
/* Section header is in 0th index... */
[label setText:string];
[view addSubview:label];
[view setBackgroundColor:[UIColor colorWithRed:166/255.0 green:177/255.0 blue:186/255.0 alpha:1.0]]; //your background color...
return view;
}

UITableView - change section header color

Hopefully this method from the UITableViewDelegate protocol will get you started:

Objective-C:

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease];
if (section == integerRepresentingYourSectionOfInterest)
[headerView setBackgroundColor:[UIColor redColor]];
else
[headerView setBackgroundColor:[UIColor clearColor]];
return headerView;
}

Swift:

func tableView(_ tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView!
{
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 30))
if (section == integerRepresentingYourSectionOfInterest) {
headerView.backgroundColor = UIColor.redColor()
} else {
headerView.backgroundColor = UIColor.clearColor()
}
return headerView
}

Updated 2017:

Swift 3:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 30))
if (section == integerRepresentingYourSectionOfInterest) {
headerView.backgroundColor = UIColor.red
} else {
headerView.backgroundColor = UIColor.clear
}
return headerView
}

Replace [UIColor redColor] with whichever UIColor you would like. You may also wish to adjust the dimensions of headerView.

How to Implement Custom Table View Section Headers and Footers with Storyboard

I know this question was for iOS 5, but for the benefit of future readers, note that effective iOS 6 we can now use dequeueReusableHeaderFooterViewWithIdentifier instead of dequeueReusableCellWithIdentifier.

So in viewDidLoad, call either registerNib:forHeaderFooterViewReuseIdentifier: or registerClass:forHeaderFooterViewReuseIdentifier:. Then in viewForHeaderInSection, call tableView:dequeueReusableHeaderFooterViewWithIdentifier:. You do not use a cell prototype with this API (it's either a NIB-based view or a programmatically created view), but this is the new API for dequeued headers and footers.

Change UITableView section header when it's on top

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()
}

Design UITableView's section header in Interface Builder

I finally solved it using this tutorial, which, largely consists of the following (adapted to my example):

  1. Create SectionHeaderView class that subclasses UIView.
  2. Create SectionHeaderView.xib file and set it's File's Owner's CustomClass to the SectionHeaderView class.
  3. Create an UIView property in the .m file like: @property (strong, nonatomic) IBOutlet UIView *viewContent;
  4. Connect the .xib's View to this viewContent outlet.
  5. Add an initializer method that looks like this:

    + (instancetype)header {

    SectionHeaderView *sectionHeaderView = [[SectionHeaderView alloc] init];

    if (sectionHeaderView) { // important part
    sectionHeaderView.viewContent = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([self class]) owner:sectionHeaderView options:nil] firstObject];

    [sectionHeaderView addSubview:sectionHeaderView.viewContent];

    return sectionHeaderView;
    }

    return nil;
    }

Then, I added an UILabel inside the .xib file and connected it to the labelCategoryName outlet and implemented the setCategoryName: method inside the SectionHeaderView class like this:

- (void)setCategoryName:(NSString *)categoryName {

self.labelCategoryName.text = categoryName;
}

I then implemented the tableView:viewForHeaderInSection: method like this:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

SectionHeaderView *sectionHeaderView = [SectionHeaderView header];

[sectionHeaderView setCategoryName:self.categoriesNames[section]];

return sectionHeaderView;
}

And it finally worked. Every section has it's own name, and also UIImageViews show up properly.

Hope it helps others that stumble over the same wrong solutions over and over again, all over the web, like I did.

[iPhone]How to customize header of Section in grouped TableView?

Implement tableView:viewForHeaderInSection: in your table view delegate.



Related Topics



Leave a reply



Submit