How to center the section headers of a UITableView - ios

I want to center the header on the tableview, however I have 2 problems. First I don't have the correct height and second the UILabel doesn't look like the default header - font/font size/color etc... Is there a better way to center it, and/or is there a way to make it look like the default header.
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger) section
{
//section text as a label
UILabel *lbl = [[UILabel alloc] init];
lbl.textAlignment = UITextAlignmentCenter;
lbl.text = #"Header";
[lbl setBackgroundColor:[UIColor clearColor]];
return lbl;
}

this should solve your issue. Tested in xcode 6 / ios8
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
[[UILabel appearanceWhenContainedIn:[UITableViewHeaderFooterView class], nil] setTextAlignment:NSTextAlignmentCenter];
return [sectionTitles objectAtIndex:section];
}

You must also implement tableView:heightForHeaderInSection to adjust your header height :
In the UITableViewDelegate Protocol Reference doc you find :
tableView:viewForHeaderInSection:
Discussion
The returned object, for example, can
be a UILabel or UIImageView object.
The table view automatically adjusts
the height of the section header to
accommodate the returned view object.
This method only works correctly when
tableView:heightForHeaderInSection: is
also implemented.
For centering the Header label you must specify the label frame before setting its aligment to center.
For getting the standart font, use SystemFontOfSize:
Also beware you are creating a memory leak you are supposed to return an autoreleased view
Try something like this :
UILabel *lbl = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)] autorelease];
lbl.textAlignment = UITextAlignmentCenter;
lbl.font = [UIFont systemFontOfSize:12];
Hope this helps,
Vincent

Volker's answer in Swift:
If you target iOS6 and later you don't have to provide your own header view if you just want to center the header title.
Just implement
- tableView:willDisplayHeaderView:forSection:
and set the textAligment property of the label:
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let headerView = view as? UITableViewHeaderFooterView {
headerView.textLabel?.textAlignment = .Center
}
}

If you target iOS6 and later you don't have to provide your own header view if you just want to center the header title.
Just implement
- tableView:willDisplayHeaderView:forSection:
and set the textAligment property of the label:
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
if([view isKindOfClass:[UITableViewHeaderFooterView class]]){
UITableViewHeaderFooterView *tableViewHeaderFooterView = (UITableViewHeaderFooterView *) view;
tableViewHeaderFooterView.textLabel.textAlignment = NSTextAlignmentCenter;
}
}

To make this method being called you should first implement
titleForHeaderInSection
then tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) method will be called
Swift Solution:
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let headerView = view as? UITableViewHeaderFooterView {
headerView.textLabel?.textAlignment = Localize().isRTL ? .Right : .Left
headerView.textLabel?.text = partsDataSource[section]
headerView.textLabel?.textColor = UIColor ( red: 0.0902, green: 0.2745, blue: 0.2745, alpha: 1.0 )
headerView.textLabel?.font = UIFont(name: UIDecorator.sharedInstance.PRIMARY_FONT, size: 14.0)
headerView.contentView.backgroundColor = UIDecorator.sharedInstance.currentTheme.lightShadeColor
}
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return " "
}

Here's my version, you'll need to take a screenshot of the normal header background, and save a 1px wide slice of it as 'my_head_bg.png' and add it to the project. This way, it'll look just exactly normal:
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
UILabel *lbl = [[[UILabel alloc] init] autorelease];
lbl.textAlignment = UITextAlignmentCenter;
lbl.font = [UIFont fontWithName:#"Helvetica-Bold" size:18];
lbl.text = #"My Centered Header";
lbl.textColor = [UIColor whiteColor];
lbl.shadowColor = [UIColor grayColor];
lbl.shadowOffset = CGSizeMake(0,1);
lbl.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"my_head_bg"]];
lbl.alpha = 0.9;
return lbl;
}

Try this
UILabel *tableHeader = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
[tableHeader setText:#"This is header"];
[tableHeader setTextAlignment:UITextAlignmentCenter];
UITableView *newTable = [[UITableView alloc] initWithFrame:CGRectMake(20, 0, 280, 200) style:UITableViewStylePlain];
[newTable setBackgroundColor:[UIColor clearColor]];
[newTable setTableHeaderView:tableHeader];
self.view = newTable;

In Xamarin:
// Center Header
public override void WillDisplayHeaderView(UITableView tableView, UIView headerView, nint section)
{
if (headerView.GetType() == typeof(UITableViewHeaderFooterView))
{
UITableViewHeaderFooterView tableViewHeaderFooterView = (UITableViewHeaderFooterView)headerView;
tableViewHeaderFooterView.TextLabel.TextAlignment = UITextAlignment.Center;
}
}

To change height, implement this method:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
return 15;
}
I am not really sure about the default header thing - that should be way easier than it is. Maybe someone has a nice background image you can use with a white font. But for the centering thing, try this:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0,0,320,15)];
label.textAlignment = UITextAlignmentCenter
label.text = #"Text Should Be Centered";

Related

Set position of the header at the beginning of the TableView

I have to set my headerView at the beginning of the table View.
It seems to be fixed please help.
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0,0,tableView.frame.size.width,40)] autorelease];
headerView.backgroundColor = [Utility consumerLightColor];
UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 250, headerView.frame.size.height)];
headerLabel.text = #"Upcoming Appointments";
headerLabel.textAlignment = NSTextAlignmentLeft;
headerLabel.textColor = [UIColor whiteColor];
if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPhone) {
headerLabel.font = [UIFont fontWithName:#"bauhaus md bt" size:15.0f];
}
else{
headerLabel.font = [UIFont fontWithName:#"bauhaus md bt" size:16.0f];
}
// // NSLog(#"title --> %#",[locationArray objectAtIndex:i]);
headerLabel.backgroundColor = [UIColor clearColor];
[headerView addSubview:headerLabel];
[headerLabel release];
return headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
if (tableView == appointmentListtableView) {
CGFloat changeheight = 40.00;
return changeheight;
}
else{
return 0.0f;
}
}
All I want is to set the position of the header view (Upcoming Appointments)at the beginning of the table View and it should not be fixed.
Maybe you need to remove table header , not section header ?
To do this you need to set:
tableView.tableHeaderView = nil
See keep always in mind,
If you want to set Static header to table view then its good & best practice to set it as a ,
yourTableView.tableHeader = yourHeaderView;
If your headers are dynamic you don't know weather how much sections want to set, then go with method,
viewForHeaderInSection:tableView
That doesn't mean you can use only one at a time not at all, You can use both at a time also,
Now comes to your case, i think you are doing something wrong in the tableViewHader, set it to nil if you don't need anymore,
But i am curious about one thing even if you have set tableViewHeader still why does it show upper & lower side of your secion header,You are setting tableViewHeader or sectionFooter or showing the UITableViewCell

How to reflect properties of UILabel to another?

Im trying to customize UITableViewController dynamically. So i have changed many properties of cell.textLabel. Now i want to copy these properties to detailTextLabel and to one label i have created through code. How it can be done?
cell.textLabel.backgroundColor = [UIColor colorWithRed:0 green:0.188235 blue:0.313725 alpha:1];
cell.textLabel.textColor=[UIColor whiteColor];
cell.textLabel.font=[UIFont fontWithName:#"HelveticaNeue" size:26];
cell.textLabel.autoresizingMask=UIViewAutoresizingFlexibleRightMargin;
This is my cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
cell.textLabel.text=[_names objectAtIndex:indexPath.row];
cell.textLabel.tag=indexPath.row;
cell.detailTextLabel.text=[_phones objectAtIndex:indexPath.row];
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"arrow.png"] ];
[imageView setFrame:CGRectMake(380,10,30,50)];
[cell addSubview:imageView];
//customize the seperator
UIView* separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1000, 1)];/// change size as you need.
separatorLineView.backgroundColor = [UIColor grayColor];// you can also put image here
[cell.contentView addSubview:separatorLineView];
cell.contentView.backgroundColor = [UIColor colorWithRed:0 green:0.188235 blue:0.313725 alpha:1];
cell.textLabel.backgroundColor = [UIColor colorWithRed:0 green:0.188235 blue:0.313725 alpha:1];
cell.textLabel.textColor=[UIColor whiteColor];
cell.textLabel.font=[UIFont fontWithName:#"HelveticaNeue" size:26];
cell.textLabel.autoresizingMask=UIViewAutoresizingFlexibleRightMargin;
//here i want to copy the properties
return cell;
}
For Swift3
class MyLabel: UILabel {
override func draw(_ rect: CGRect) {
super.draw(rect)
backgroundColor = UIColor(red: 0, green: 0.188235, blue: 0.313725, alpha: 1)
textColor = UIColor.white
font = UIFont(name: "HelveticaNeue", size: 26)
autoresizingMask = .flexibleRightMargin
}
}
Create a subclass of UILabel in this way.
#import "MyLabel.h"
#implementation MyLabel
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
self.backgroundColor = [UIColor colorWithRed:0 green:0.188235 blue:0.313725 alpha:1];
self.textColor=[UIColor whiteColor];
self.font=[UIFont fontWithName:#"HelveticaNeue" size:26];
self.autoresizingMask=UIViewAutoresizingFlexibleRightMargin;
}
#end
And now create an object of this MyLabel and your properties will be set automatically and also just assign this class to your label through storyboard to the label in your cell.
Subclassing is the best way for implementing reusable code.
Or else you can even create an extension of class or even an class method in some class which accepts the UILabel and sets the properties but this all are not the best practices. Another problem with extensions is the you can only use self but not super. This may create problems in future when you have to extend the properties.
I hope I am clear and helpful.
You can use this method to make all the labels of UITabelViewCell to same property
Here just loop through the subViews and check whether the subview is of UILabel, If it is of UILabel then set the property you want.
My Code :
- (void)formatTheLabelForCell:(UITableViewCell *)cell
{
for (UIView *view in cell.contentView.subviews) {
if ([view isKindOfClass:[UILabel class]]) {
UILabel *lbl = (UILabel *)view;
lbl.backgroundColor = [UIColor colorWithRed:0 green:0.188235 blue:0.313725 alpha:1];
lbl.textColor=[UIColor whiteColor];
lbl.font=[UIFont fontWithName:#"HelveticaNeue" size:26];
lbl.autoresizingMask=UIViewAutoresizingFlexibleRightMargin;
}
}
}
Instead of configuring cell in cellForRowAtIndexPath, it's better if you use custom cell. Add imageView & separatorLineView in your Storyboard/ Nib itself. This way all cells are generated with these default properties. Also if you need to configure something through code, you can code it in your CustomCell.m file like this:
class CustomCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
self.textLabel.backgroundColor = UIColor.redColor
//do other configurations
}
Edit: Downloading images from web may be the reason for taking long time loading cells. Try downloading images asynchronously. You can also use this library: SDWebImage
Note: I know you want it in Objective C, above code in Swift is just for illustration.
As for swift, you can do this, it will copy all the attributes you applied to textLabel to detailTextLabel.
cell.detailTextLabel.attributedText = cell.textLabel.attributedText
First of all I don't think that there is a function to copy specific properties of a any UIKit component in iOS SDK. Therefore for you will have to write a custom function for this. Additionally there are some issues with your "cellForRowAtIndexPath" as pointed out by others in comments.
There are different solutions to this.
Solution 1:
Write a function in your view controller which take two labels as parameters and copy your desired values.
-(void)copyPropertiesFrom:(UILabel*)label1 toLabel:(UILabel*)label2{
label2.backgroundColor = label1.backgroundColor;
label2.textColor = label1.textColor;
label2.font = label1.font;
label2.autoresizingMask = label1.autoresizingMask;
}
In cellForRowAtIndexPath where you want to copy do this
[self copyPropertiesFrom:cell.titleLabel toLabel:cell.detailTextLabel];
Solution 2(Recommended): This is best in my little experience because you can reuse it in other view controllers. There might be a better approach than this.
Create a category of UILabel. Check this link How do I create a category in Xcode 6 or higher? and also this https://code.tutsplus.com/tutorials/objective-c-categories--mobile-10648
Your function within category will look like this.
-(void)formatLabelToMyStyle{
self.backgroundColor = [UIColor colorWithRed:0 green:0.188235 blue:0.313725 alpha:1];
self.textColor = [UIColor whiteColor];
self.font = [UIFont fontWithName:#"HelveticaNeue" size:26];
self.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
}
You will include header file of category and call this function in your cellForRowAtIndexPath like this
[cell.titleLabel formatLabelToMyStyle];
[cell.detailTextLabel formatLabelToMyStyle];
[cell.customTextLabel formatLabelToMyStyle];
And as for your cellForRowAtIndexPath, larme mentioned in comments "Don't add subview like that in cells because cells are reused" This will keep adding views to your cell hence causing memory issues, Specially when you have large number of cell which in your case is true.
You could use a Category for UILabel or use a subclass of UILabel that should share the same styling.
A Category for the UILabel could look like:
// UILabel+CustomStyle.h
#import <UIKit/UIKit.h>
#interface UILabel (CustomStyle)
-(void) applyCustomStyle;
#end
.m file:
// UILabel+CustomStyle.m
#import "UILabel+CustomStyle.h"
#implementation UILabel (CustomStyle)
-(void) applyCustomStyle {
self.backgroundColor = [UIColor colorWithRed: 0 green: 0.188235 blue: 0.313725 alpha: 1];
self.textColor = [UIColor whiteColor];
self.font = [UIFont fontWithName: #"HelveticaNeue" size: 26];
self.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
}
#end
Then you can apply the same styling by simply calling:
#import "UILabel+CustomStyle.h"
[label applyCustomStyle];
If you want to use same label configuration to many places in project. Just subclass as #NikhilManapure said.
OR
If you want to apply same properties to TableViewCell textLabel and detailTextLabel. You should subclass TableViewCell and override Label properties in drawrect method.
Objective-C
#import <UIKit/UIKit.h>
#interface PropertiesCell : UITableViewCell
#end
#import "PropertiesCell.h"
#implementation PropertiesCell
- (void)awakeFromNib {
[super awakeFromNib];
// Initialization code
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)drawRect:(CGRect)rect {
[super drawRect:rect];
[self cellLabelConfigure:self.textLabel];
[self cellLabelConfigure:self.detailTextLabel];
}
- (void)cellLabelConfigure:(UILabel*) contentLabel {
contentLabel.backgroundColor = [UIColor colorWithRed:0 green:0.188235 blue:0.313725 alpha:1];
contentLabel.textColor=[UIColor whiteColor];
contentLabel.font=[UIFont fontWithName:#"HelveticaNeue" size:26];
contentLabel.autoresizingMask=UIViewAutoresizingFlexibleRightMargin;
}
#end
Swift
class PropertiesCell: UITableViewCell {
override func draw(_ rect: CGRect) {
super.draw(rect)
cellLabelsConfigure(contentLabel: self.textLabel)
cellLabelsConfigure(contentLabel: self.detailTextLabel)
}
func cellLabelsConfigure(contentLabel: UILabel?) {
contentLabel?.backgroundColor = UIColor(red: 0.0, green: 0.188, blue: 0.313, alpha: 1.0)
contentLabel?.textColor = UIColor.white
contentLabel?.font = UIFont(name: "HelveticaNeue", size: 26.0)
contentLabel?.autoresizingMask = UIViewAutoresizing.flexibleRightMargin
}
}
In storyboard change cell class name to PropertiesCell
Create an extension class and use this copy method to pass all the properties you want to the new label.
#implementation UILabel (Copy)
- (UILabel *)copyProperties {
UILabel *label = [UILabel new];
[self copyPropertiesWithLabel:label];
return label;
}
- (void)copyPropertiesWithLabel:(UILabel *)label {
label.backgroundColor = self.backgroundColor;
label.textColor = self.textColor;
label.font = self.font;
label.autoresizingMask = self.autoresizingMask;
// Add more properties
}
#end
Usage:
// cell.textLabel has now all the properties
[theLabelToBeCopied copyPropertiesWithLabel:cell.textLabel];
Swift3 version:
extension UILabel {
func copyProperties() -> UILabel {
var label = UILabel()
self.copyProperties(with: label)
return label
}
func copyProperties(with label: UILabel) {
label.backgroundColor = self.backgroundColor
label.textColor = self.textColor
label.font = self.font
label.autoresizingMask = self.autoresizingMask
// Add more properties
}
}
Usage:
theLabelToBeCopied.copyProperties(with: cell.textLabel)
you can do this for swift.it will copy for all attributes (textLabel to detailTextLabel).i think #Nikhil Manapure given exact answer.
cell.detailTextLabel.attributedText = cell.textLabel.attributedText

UITableViewCell scroll over custom UITableView header title

I have a simple UITableViewController which contains about 40 UITableViewCells and the UITableViewController is embedded in a UITabBarController. The UITableViewController is created in Storyboard.
I am overriding the custom UITableViewHeader Text so that I can have a few guides there for users. I am noticing some really weird behaviour with this as represented by the following images:
As can be seen, the UITableView scrolls, but the header text remains there and it looks terrible.
Here is how I'm setting up the custom header:
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
// Custom label for the section header titles
UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(25, 0, tableView.frame.size.width, 110)];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.numberOfLines = 0;
[label setFont:[UIFont systemFontOfSize:17.0]];
if (section == 0)
{
label.text = #" Add to this by marking a leaflet or video as a favourite.\n\nYou can do this by swiping left on any leaflet or video cell.";
}
return label;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
CGFloat headerHeight = 0;
headerHeight = 110;
return headerHeight;
}
I have worked with different sizes, but no matter what I do, it still behaves in the same way.
If anyone has any thoughts or guidance on this, that would really be appreciated. I just want the header text to also scroll up with the table view and to therefore be hidden from view when scrolling.
You can add your header as the tableHeaderView like this:
- (void)viewDidLoad {
[super viewDidLoad];
UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(25, 0, self.tableView.frame.size.width, 110)];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor blackColor];
label.numberOfLines = 0;
[label setFont:[UIFont systemFontOfSize:17.0]];
label.text = #" Add to this by marking a leaflet or video as a favourite.\n\nYou can do this by swiping left on any leaflet or video cell.";
self.tableView.tableHeaderView = label;
}
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
// Custom label for the section header titles
UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 110)];
UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(25, 0, tableView.frame.size.width, 110)];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.numberOfLines = 0;
[label setFont:[UIFont systemFontOfSize:17.0]];
if (section == 0) {
label.text = #" Add to this by marking a leaflet or video as a favourite.\n\nYou can do this by swiping left on any leaflet or video cell.";
}
[view addSubView:label];
[view setBackgroundColor:[UIColor blueColor]]; // the color for background
return view;}

How to correct the tableview section header frame according to the orientation / UITableView width

I have a UITableView with grouped style - and I have a custom header view:
+ (UIView *) viewForHeaderWithText: (NSString*) title
{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
UIView *viewHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 20)];
UILabel *label = [[UILabel alloc] init];
label.backgroundColor = [UIColor clearColor];
label.frame = CGRectMake(10.0f, 0.0f, 300.0f, 20.0f);
label.font = [UIFont systemFontOfSize:12.0f];
label.textColor = [UIColor blackColor];
label.textAlignment = NSTextAlignmentLeft;
label.text = title;
if (!IS_OS_7_OR_LATER) {
label.textColor = [UIColor lightGrayColor];
}
[viewHeader addSubview:label];
return viewHeader;
}
}
So the section header width frame is fixed.
but For different orientation and way of presenting the UITableViewController the cell width (iOS6) is changed - as u can see on the screenshots. But I need to make offset for the section title and cell equal.
Now I have:
What I need:
I tried to change the cell width - but not solve this.. Any help?
You need to impelement this below uitableView delegate method:-
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

UITableView extend different background color below cells

I have a UITableView that I have given a headerView that has a green background. I have also given the UITableView that same green background color so that when the tableView is pulled down it feels like a seemless color above the tableView. Works perfectly.
The problem is my tableView only has 4 rows, and below that it shows the green color again.
How can I show white below the rows instead so that I only see the green background color when pulling down the tableView?
You can add an extra top view, same as in this answer to UIRefreshControl Background Color:
CGRect frame = self.tableView.bounds;
frame.origin.y = -frame.size.height;
UIView *bgView = [[UIView alloc] initWithFrame:frame];
bgView.backgroundColor = [UIColor greenColor];
[self.tableView insertSubview:bgView atIndex:0];
You could add a fifth cell with no content, and make it, say 400 points high, and limit the size of the table's contentView so that you can't scroll to the bottom of that cell.
-(void)viewWillLayoutSubviews {
self.tableView.contentSize = CGSizeMake(self.tableView.frame.size.width, 500);
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
CGFloat h = (indexPath.row == 4)? 400:44;
return h;
}
Putting the contentSize setting in viewWillLayoutSubviews ensures that it will be reset to that value if you rotate your device.
as I said in these comments, in this way the headerView will be under the navigationBar and if you pull down the tableview you will see the headerView green. So you can set white color for tableView:
(i tested it and work)
-(void) viewDidLoad {
self.tableView.backgroundColor = [UIColor whiteColor];
headerView = [[UIView alloc] init];
headerView.backgroundColor = [UIColor greenColor];
UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, -50, 320, 120)];
lab.backgroundColor = [UIColor greenColor];
[headerView addSubview:lab];
self.tableView.tableHeaderView = headerView;
}
#pragma mark - Table view data source
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 80;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
return headerView;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
Same as the accepted answer - in Swift 5:
var frame : CGRect = self.tableView.bounds
frame.origin.y = -frame.size.height
let bgView : UIView = UIView.init(frame: frame)
bgView.backgroundColor = UIColor.green
self.tableView.insertSubview(bgView, at: 0)
Also add the following code (right after the above code) to make sure it works for other sized devices:
bgView.translatesAutoresizingMaskIntoConstraints = true
bgView.autoresizingMask = [UIView.AutoresizingMask.flexibleWidth]

Resources