UITableView clear background - ios

I realize that iOS 7 has not officially been released and we should not discuss it BUT I am going crazy trying to figure out this problem. On iOS 6, my table view was transparent and looked great. First time running iOS 7, and the background is white.
I have tried making the table backgroundColor, cell color etc etc to UIColor clearColor but have no change.
How to fix this problem?

// Fix for iOS 7 to clear backgroundColor
cell.backgroundColor = [UIColor clearColor];
cell.backgroundView = [[UIView new] autorelease];
cell.selectedBackgroundView = [[UIView new] autorelease];
in cellForRowAtIndexPath
Also, make sure that your tableview actually has transparent background (in storyboard):

Put this:
cell.backgroundColor = [UIColor clearColor];
In this section:
cellForRowAtIndexPath

Try setting backgroundView to nil first.
[self.tableView setBackgroundView:nil];
[self.tableView setBackgroundColor:[UIColor clearColor]];
Not sure if this is a change in documentation with iOS7 or has always been there and just did not affect background color, but per UITableView Class Reference #property backgroundView
"You must set this property to nil to set the background color of the table view."
edit: corrected code syntax

This has been answered, but incorrectly in a lot of ways.
You need to implement the below delegate method:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
[cell setBackgroundColor:[UIColor clearColor]];
}
You can't put the fix in cellForRowAtIndexPath because that is after the cell is rendered, and it will flash a white background before the background gets set to clear (on slower devices).
Use this delegate method and your problems are solved!

Actually the officially correct place to change cell background color is different according to documentation (UITableViewCell Class Reference):
Whether you use a predefined or custom cell, you can change the cell’s
background using the backgroundView property or by changing the
inherited backgroundColor property. In iOS 7, cells have a white
background by default; in earlier versions of iOS, cells inherit the
background color of the enclosing table view. If you want to change
the background color of a cell, do so in the
tableView:willDisplayCell:forRowAtIndexPath: method of your table view
delegate.

swift 3, 4 and 5
cell.backgroundColor = UIColor.clear

This is quite a frustrating problem. Here's my current solution:
Add this to your UITableViewCell subclass.
- (void)didMoveToSuperview {
[super didMoveToSuperview];
self.backgroundColor = [UIColor clearColor];
}

This did only work for me when i edited a clear background color for each cell and a clear color for the table itself.. BOTH PROGRAMMATICALLY
to set the clear color for the table:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
initMenu()
myTableView.backgroundColor = UIColor.clearColor()
}
to set the color for the cells:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("tablecellid", forIndexPath: indexPath)
cell.backgroundColor = UIColor.clearColor()
return cell
}

This worked for me in iOS7+:
self.tableView.backgroundColor =[UIColor blueColor];
self.tableView.opaque = NO;
self.tableView.backgroundView = nil;`
and then in cellForRowAtIndexPath:
cell.backgroundColor = [UIColor clearColor];

try this code snippet
cell.contentView.backgroundColor = [UIColor clearColor];
cell.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.5];

First set
tableView.backgroundColor = [UIColor clearColor];
Second set
tableCell.backgroundColor = [UIColor clearColor];

One thing to nice. The default color of UITable seems to be white (I don't know why)
But better change that.

create IB Outlet for table view
#IBOutlet weak var yourTable : UITableView!
in view load
override func viewDidLoad() {
yourTable.delegate = self
yourTable.dataSource = self
yourTable.backgroundColor = UIColor.clearColor()
}
if you want to clear color of Cell also do this in
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
cell.backgroundColor = UIColor.clearColor()
}

In my app, I had to set the backgroundColor on my UITableViewCell class to [UIColor clearColor] color when I updated for iOS 7.

Try
[myTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
[myTable setSeparatorInset:UIEdgeInsetsZero];
And
cell.backgroundColor = [UIColor clearColor];

In my case the cell was created using a xib. it seems like interface builder on xcode5 has trouble setting clearColor to the cell.backgroundColor.
All I needed to do was indeed to set
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// get the cell from the nib
//then force the backgroundColor
cell.backgroundColor = [UIColor clearColor]
return cell;
}

Just select Clear Color on View Background for the table and for the cell also.

swift 3
override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundColor = UIColor.clear
}

// Fix iOS 7 clear backgroundColor compatibility
// I Think this two lines only are enough
cell.backgroundColor = [UIColor clearColor];
cell.selectedBackgroundView = [[UIView new] autorelease];

In swift 3
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath)
cell.backgroundColor = .clear
cell.backgroundView = UIView()
cell.selectedBackgroundView = UIView()
return cell
}

Set
tableView.backgroundColor = [UIColor clearColor];
in viewDidLoad.
if this is not working, try:
tableView.backgroundView = nil;

Related

How can I change the cell color inside GetCell()?

I'm using the Xamarin.SideMenu NuGet Package.
https://github.com/TheEightBot/Xamarin.SideMenu
Everything works fine, except that I need to make a few customizations. Mainly I need to change the font color of the flyout drawer menu options.
I've tried setting cell.TintColor = UIColor.Red;, but it didn't do anything.
Here is my code:
public override UITableViewCell GetCell(UITableView tableView, Foundation.NSIndexPath indexPath)
{
var cell = tableView.DequeueReusableCell(“VibrantCell”);
cell.TextLabel.Text = “Index ” + indexPath.Row;
cell.TintColor = UIColor.Blue;
cell.BackgroundColor = UIColor.Green;
return cell;
}
[Export(“tableView:willDisplayCell:forRowAtIndexPath:“)]
public override void WillDisplay(UITableView tableView, UITableViewCell cell, Foundation.NSIndexPath indexPath)
{
cell.TintColor = UIColor.Red; // no effect?
cell.BackgroundColor = UIColor.Green; // no effect?
}
For some reason the color is not changing and is still black.
Is there a way I can get a flyoutdrawer on native Xamarin.iOS where the text color is something other than black?
Thank you very much.
You should not be modifying the cell itself. You should be modifying the cell's TextLabel property.
So it should be:
cell.TextLabel.TextColor = UIColor.Red;

disable the uitableview highlighting but allow the selection of individual cells

when you tap on a cell the row gets selected and highlighted.Now what i want to do is disable the highlighting but allow the selection.Is there a way around it.There is question that answers this but it disables both the selection and highlighting.
You can just set the cell's selection style to "None" from Storyboard:
Or from code:
cell.selectionStyle = UITableViewCellSelectionStyleNone;
For Swift 3:
cell.selectionStyle = UITableViewCellSelectionStyle.none
For Swift 4 & above:
cell.selectionStyle = .none
Change UITableViewCell's selectedBackgroundView color to transparent.
let clearView = UIView()
clearView.backgroundColor = UIColor.clearColor() // Whatever color you like
UITableViewCell.appearance().selectedBackgroundView = clearView
or to set for a specific cell:
cell.backgroundView = clearView
Try setting cell selection style to None -
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
This will solve your problem
For Swift 3.0:
cell.selectionStyle = .none
For Swift:
UITableViewCell.selectionStyle = UITableViewCellSelectionStyle.None;
Or when you subclass a cell in swift:
class CustomCell : UITableViewCell {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
selectionStyle = .None
}
}
in swift 3
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
To add a custom color use the below code. And to make it transparent use alpha: 0.0
cell.selectedBackgroundView = UIView(frame: CGRect.zero)
cell.selectedBackgroundView?.backgroundColor = UIColor(red:0.27, green:0.71, blue:0.73, alpha:1.0)
If you use custom color and want to give it rounded corner look use:
cell.layer.cornerRadius = 8
Also, use this for better animation and feel
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
For those looking for a programmatic way in Swift 3
cell.selectionStyle = UITableViewCellSelectionStyle.none
You can set the selection property of the cell itself in the storyboard
For Objc:
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
- (void)viewDidLoad {
[super viewDidLoad];
_tableView.allowsSelection = YES;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
.. .. .. ..
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
. . . . ..
}
For Swift 5 the best way is:
cell.selectionStyle = .none
Here is the solution for swift 3,works even in editing mode
cell.selectionStyle = .gray
cell.selectedBackgroundView = {
let colorView = UIView()
colorView.backgroundColor = UIColor.black.withAlphaComponent(0.0)
//change the alpha value or color to match with you UI/UX
return colorView
}()

UITableView set background color

I change the background color of the UITableViewCells in the tableView:cellForRowAtIndexPath method
if(indexPath.row % 2 == 0){
cell.backgroundColor = ...
} else{
cell.backgroundColor = ...
}
But that only change the color of the cell amount specified in tableView:numberOfRowsInSection (As seen in the attached picture, there are white cells after the first four)
Is it possible to change the color of all cells that are displayed on screen?
Open Storyboard
Select your UITableView
Open Attribute inspector
Scroll to View group
Select background color for entire table.
If you want the cell background color to continue to alternate, then you need to lie about how many rows are in the table. Specifically, in tableView:numberOfRowsInSection you need to always return a number that will fill the screen, and in tableView:cellForRowAtIndexPath, return a blank cell for rows that are beyond the end of the table. The following code demonstrates how to do this, assuming that self.dataArray is an NSArray of NSStrings.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ( self.dataArray.count < 10 )
return( 10 );
else
return( self.dataArray.count );
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"SimpleCell"];
if ( indexPath.row % 2 == 0 )
cell.backgroundColor = [UIColor orangeColor];
else
cell.backgroundColor = [UIColor redColor];
if ( indexPath.row < self.dataArray.count )
cell.textLabel.text = self.dataArray[indexPath.row];
else
cell.textLabel.text = nil;
return cell;
}
Try like this:-
self.tableView.backgroundView.backgroundColor = [UIColor blueColor];
In swift, you can change tableview background color or you can set image to tableview background color like this;
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png")!)
self.tableView.backgroundColor = UIColor.clearColor()
}
// change cell text color and background color
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.backgroundColor = UIColor.clearColor()
}
I used this to color alternate cell in a table view
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell,
forRowAtIndexPath indexPath: NSIndexPath) {
if (indexPath.row % 2 == 0)
{
cell.backgroundColor = UIColor.grayColor()
}
else
{
cell.backgroundColor = UIColor.whiteColor()
}
}
You need to set the tableview's backgroundView to nil and its backgroundColor to the desired color.
For SWIFT
Thanks to #Irshad Qureshi I was able to get alternating background colors for my prototype cells by adding the following in my cellForRowAtIndexPath:
if (indexPath.row % 2 == 0)
{
cell!.backgroundColor = UIColor.groupTableViewBackgroundColor()
}
else
{
cell!.backgroundColor = UIColor.whiteColor()
}
Swift 5 and up
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
//Set Clear Backcolor
//cell.backgroundColor = .clear
//or in your case
if ( indexPath.row % 2 == 0 )
cell.backgroundColor = .orange
else
cell.backgroundColor = .red
}

Add button to UITableViewCell's Accessory View

Goal: when a user selects a cell, a button is added to that cell. Within my didSelectRowAtIndexPath function I have the following:
UIButton *downloadButton = [[UIButton alloc] init];
downloadButton.titleLabel.text = #"Download";
[downloadButton setFrame:CGRectMake(40, 0, 100, 20)];
[[self.tableView cellForRowAtIndexPath:indexPath].accessoryView addSubview:downloadButton];
[[self.tableView cellForRowAtIndexPath:indexPath].accessoryView setNeedsLayout];
[downloadButton release];
Unfortunately that doesn't seem to do anything. Am I redrawing the cell correction? Do I need to add it another way?
Try this block of code instead of the block you provided above:
UIButton *downloadButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[downloadButton setTitle:#"Download" forState:UIControlStateNormal];
[downloadButton setFrame:CGRectMake(0, 0, 100, 35)];
[tableView cellForRowAtIndexPath:indexPath].accessoryView = downloadButton;
This should display the button, but you will still need to hook up some kind of selector to it using addTarget. (I am not sure if listening in for the accessoryButtonTappedForRowWithIndexPath delegate will work in this case, try that first and see if it fires on your button press.)
I had the same problem. Attempting to set the accessoryView to a UIButton which had an image caused it to not appear.
The trick was to call [UIButton sizeToFit], to ensure its frame is set properly.
Assign the button as the accessory view rather than a subview of the accessory view.
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
cell.accessoryView = downloadButton;
Swift 4 and above: Add button to UITableViewCell's Accessory View
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = Table.dequeueReusableCell(withIdentifier: "identifier", for: indexPath)
let accessoryButton = UIButton(type: .custom)
accessoryButton.addTarget(self, action: #selector(deleteCell(sender:)), for: .touchUpInside)
accessoryButton.setImage("Add_image", for: .normal)
accessoryButton.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
accessoryButton.contentMode = .scaleAspectFit
cell.accessoryView = accessoryButton as UIView
return cell
}
Add Selector Method
func deleteCell(sender: AnyObject)
{
let pointInTable: CGPoint = sender.convert(sender.bounds.origin, to: self.Table)
let cellIndexPath = self.Table.indexPathForRow(at: pointInTable)
let point = cellIndexPath!.row
}
let button = UIButton(type:.roundedRect)
button.setTitle("A", for: .normal)
button.sizeToFit()
cell.accessoryView = button
Try This:
[[self.tableView cellForRowAtIndexPath:indexPath].contentView addSubview:downloadButton];
And remember to delete that button when the cell is being reused.
Here is my example for a the full solution to your request:
In my UITableViewCell subclass (I call it RNWNewItemCell):
-(void)configureCell...
{
// create the button
self.btnSeekDuplicate = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 22, 22)];
// just make it yellow until we get our real image..
self.btnSeekDuplicate.backgroundColor = [UIColor yellowColor];
// add the handler for the button press
[self.btnSeekDuplicate addTarget:self
action:#selector(seekDuplicateButtonWasPressed)
forControlEvents:UIControlEventTouchUpInside];
// make it visible in the table cell...
[self setAccessoryView:self.btnSeekDuplicate];
}
- (void)seekDuplicateButtonWasPressed
{
do something...
}
In my Table Code that uses the cell...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...
RNWNewItemCell *aNewItemCell = [tableView dequeueReusableCellWithIdentifier:cellIdentifierForNewItemCell forIndexPath:indexPath];
[aNewItemCell configureCell...]
...
}
Note that accessoryButtonTappedForRowWithIndexPath is NOT called when you set the table cell's accessoryView. Probably because they assume you are using a view that responds to events.
Its always best to add any views that you are adding to a cell to cell.contentView.
Also try to check if the accessoryView is nil.
Swift
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
let accessoryButton = UIButton.buttonWithType(UIButtonType.ContactAdd) as! UIButton
cell.accessoryView = accessoryButton
return cell
}
use this :
cell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton;

UITableView - change section header color

How can I change color of a section header in UITableView?
EDIT: The answer provided by DJ-S should be considered for iOS 6 and above. The accepted answer is out of date.
This is an old question, but I think the answer needs to be updated.
This method does not involve defining and creating your own custom view.
In iOS 6 and up, you can easily change the background color and the text color by defining the
-(void)tableView:(UITableView *)tableView
willDisplayHeaderView:(UIView *)view
forSection:(NSInteger)section
section delegate method
For example:
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
// Background color
view.tintColor = [UIColor blackColor];
// Text Color
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
[header.textLabel setTextColor:[UIColor whiteColor]];
// Another way to set the background color
// Note: does not preserve gradient effect of original header
// header.contentView.backgroundColor = [UIColor blackColor];
}
Taken from my post here:
https://happyteamlabs.com/blog/ios-how-to-customize-table-view-header-and-footer-colors/
Swift 3 / 4
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
view.tintColor = UIColor.red
let header = view as! UITableViewHeaderFooterView
header.textLabel?.textColor = UIColor.white
}
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.
Here's how to change the text color.
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(10, 3, tableView.bounds.size.width - 10, 18)] autorelease];
label.text = #"Section Header Text Here";
label.textColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.75];
label.backgroundColor = [UIColor clearColor];
[headerView addSubview:label];
You can do this if you want header with custom color. This solution works great since iOS 6.0.
Objective C:
[[UITableViewHeaderFooterView appearance] setTintColor:[UIColor redColor]];
Swift:
UITableViewHeaderFooterView.appearance().tintColor = .white
The following solution works for Swift 1.2 with iOS 8+
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// This changes the header background
view.tintColor = UIColor.blueColor()
// Gets the header view as a UITableViewHeaderFooterView and changes the text colour
var headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
headerView.textLabel.textColor = UIColor.redColor()
}
Setting the background color on UITableViewHeaderFooterView has been deprecated. Please use contentView.backgroundColor instead.
You can do it on main.storyboard in about 2 seconds.
Select Table View
Go to Attributes Inspector
List item
Scroll down to View subheading
Change "background"
Don't forget to add this piece of code from the delegate or your view will be cut off or appear behind the table in some cases, relative to the height of your view/label.
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 30;
}
If you don't want to create a custom view, you can also change the color like this (requires iOS 6):
-(void) tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
if ([view isKindOfClass: [UITableViewHeaderFooterView class]]) {
UITableViewHeaderFooterView* castView = (UITableViewHeaderFooterView*) view;
UIView* content = castView.contentView;
UIColor* color = [UIColor colorWithWhite:0.85 alpha:1.]; // substitute your color here
content.backgroundColor = color;
}
}
For swift 5 +
In willDisplayHeaderView Method
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
//For Header Background Color
view.tintColor = .black
// For Header Text Color
let header = view as! UITableViewHeaderFooterView
header.textLabel?.textColor = .white
}
I hope this helps you :]
Set the background and text color of section area: (Thanks to William Jockusch and Dj S)
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
if ([view isKindOfClass: [UITableViewHeaderFooterView class]]) {
UITableViewHeaderFooterView* castView = (UITableViewHeaderFooterView*) view;
castView.contentView.backgroundColor = [UIColor grayColor];
[castView.textLabel setTextColor:[UIColor grayColor]];
}
}
Swift 4
To change the background color, text label color and font for the Header View of a UITableView Section, simply override willDisplayHeaderView for your table view like so:
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
header.backgroundView?.backgroundColor = .white
header.textLabel?.textColor = .black
header.textLabel?.font = UIFont(name: "Helvetica-Bold", size: 14)
}
This worked perfectly for me; hope it does help you too!
Here's how to add an image in header view:
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease];
UIImageView *headerImage = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"top-gery-bar.png"]] autorelease];
headerImage.frame = CGRectMake(0, 0, tableView.bounds.size.width, 30);
[headerView addSubview:headerImage];
return headerView;
}
For iOS8 (Beta) and Swift choose the RGB Color you want and try this:
override func tableView(tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView! {
var header :UITableViewHeaderFooterView = UITableViewHeaderFooterView()
header.contentView.backgroundColor = UIColor(red: 254.0/255.0, green: 190.0/255.0, blue: 127.0/255.0, alpha: 1)
return header
}
(The "override" is there since i´m using the UITableViewController instead of a normal UIViewController in my project, but it´s not mandatory for changing the section header color)
The text of your header will still be seen.
Note that you will need to adjust the section header height.
Good Luck.
SWIFT 2
I was able to successfully change the section background color with an added blur effect (which is really cool). To change the background color of section easily:
First go to Storyboard and select the Table View
Go to Attributes Inspector
List item
Scroll down to View
Change "Background"
Then for blur effect, add to code:
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// This is the blur effect
let blurEffect = UIBlurEffect(style: .Light)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
// Gets the header view as a UITableViewHeaderFooterView and changes the text colour and adds above blur effect
let headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
headerView.textLabel!.textColor = UIColor.darkGrayColor()
headerView.textLabel!.font = UIFont(name: "HelveticaNeue-Light", size: 13)
headerView.tintColor = .groupTableViewBackgroundColor()
headerView.backgroundView = blurEffectView
}
Swift 4 makes it very easy. Simply add this to your class and set the color as needed.
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.backgroundColor = UIColor(red: 0.094, green: 0.239, blue: 0.424, alpha: 1.0)
}
or if a simple color
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.backgroundColor = UIColor.white
}
Updated for Swift 5
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.tintColor = UIColor(red: 0.094, green: 0.239, blue: 0.424, alpha: 1.0)
}
or if a simple color
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
view.tintColor = UIColor.white
}
For me none of above works after wasting 2 hours what this is the solution. In my case it was custom view but I cannot able to change it from storyboard and view's awakeFromNib for some reason.
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as! UITableViewHeaderFooterView
header.contentView.backgroundColor = .white
}
I know its answered, just in case, In Swift use the following
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let tableViewWidth = self.tableView.bounds
let headerView = UIView(frame: CGRectMake(0, 0, tableViewWidth.size.width, self.tableView.sectionHeaderHeight))
headerView.backgroundColor = UIColor.greenColor()
return headerView
}
iOS 8+
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
tableView.tableHeaderView?.backgroundColor = UIColor.blue()
}
Based on #Dj S answer, using Swift 3. This works great on iOS 10.
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// Background color
view.tintColor = UIColor.black
// Text Color
let headerView = view as! UITableViewHeaderFooterView
headerView.textLabel?.textColor = UIColor.white
}
I have a project using static table view cells, in iOS 7.x. willDisplayHeaderView does not fire. However, this method works ok:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
NSLog(#"%s", __FUNCTION__);
CGRect headerFrame = CGRectMake(x, y, w, h);
UIView *headerView = [[UIView alloc] initWithFrame:headerFrame];
headerView.backgroundColor = [UIColor blackColor];
-(void) tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view
forSection:(NSInteger)section
{
if ([view isKindOfClass: [UITableViewHeaderFooterView class]])
{
UITableViewHeaderFooterView *castView = (UITableViewHeaderFooterView *) view;
UIView *content = castView.contentView;
UIColor *color = [UIColor whiteColor]; // substitute your color here
content.backgroundColor = color;
[castView.textLabel setTextColor:[UIColor blackColor]];
}
}
I think this code is not so bad.
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(MyHeaderView.reuseIdentifier) as MyHeaderView
let backgroundView = UIView()
backgroundView.backgroundColor = UIColor.whiteColor()
headerView.backgroundView = backgroundView
headerView.textLabel.text = "hello"
return headerView
}
In iOS 7.0.4 I created a custom header with it's own XIB. Nothing mentioned here before worked. It had to be the subclass of the UITableViewHeaderFooterView to work with the dequeueReusableHeaderFooterViewWithIdentifier: and it seems that class is very stubborn regarding the background color. So finally I added an UIView (you could do it either with code or IB) with name customBackgroudView, and then set it's backgroundColor property. In layoutSubviews: I set that view's frame to bounds. It work with iOS 7 and gives no glitches.
// in MyTableHeaderView.xib drop an UIView at top of the first child of the owner
// first child becomes contentView
// in MyTableHeaderView.h
#property (nonatomic, weak) IBOutlet UIView * customBackgroundView;
// in MyTableHeaderView.m
-(void)layoutSubviews;
{
[super layoutSubviews];
self.customBackgroundView.frame = self.bounds;
}
// if you don't have XIB / use IB, put in the initializer:
-(id)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
...
UIView * customBackgroundView = [[UIView alloc] init];
[self.contentView addSubview:customBackgroundView];
_customBackgroundView = customBackgroundView;
...
}
// in MyTableViewController.m
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
MyTableHeaderView * header = [self.tableView
dequeueReusableHeaderFooterViewWithIdentifier:#"MyTableHeaderView"];
header.customBackgroundView.backgroundColor = [UIColor redColor];
return header;
}
Just change the color of layer of the header view
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease];
headerView.layer.backgroundColor = [UIColor clearColor].CGColor
}
If anyone needs swift, keeps title:
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0,y: 0,width: self.tableView.frame.width, height: 30))
view.backgroundColor = UIColor.redColor()
let label = UILabel(frame: CGRect(x: 15,y: 5,width: 200,height: 25))
label.text = self.tableView(tableView, titleForHeaderInSection: section)
view.addSubview(label)
return view
}
I got message from Xcode through console log
[TableView] Setting the background color on
UITableViewHeaderFooterView has been deprecated. Please set a custom
UIView with your desired background color to the backgroundView
property instead.
Then I just create a new UIView and lay it as background of HeaderView.
Not a good solution but it easy as Xcode said.
In my case, It worked like this:
let headerIdentifier = "HeaderIdentifier"
let header = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: headerIdentifier)
header.contentView.backgroundColor = UIColor.white
Just set the background color of the background view:
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
let tableHeader = view as! UITableViewHeaderFooterView
tableHeader.backgroundView?.backgroundColor = UIColor.white
}
If you are using a custom header view:
class YourCustomHeaderFooterView: UITableViewHeaderFooterView {
override func awakeFromNib() {
super.awakeFromNib()
self.contentView.backgroundColor = .white //Or any color you want
}
}

Resources