How do I remove the lines indicated in the picture? I have tried the following suggestions and none of them have worked for me,
How do I remove the borders of a UITableView?
Remove separator line for only one cell
Hide separator line on one UITableViewCell
This is my current code in cellForRowAt:
if (indexPath.row == place_sections[indexPath.section].rows.count - 1) {
cell.separatorInset.left = 1000
//cell.layer.borderWidth = 0
//cell.separatorInset = UIEdgeInsetsMake(0, 160, 0, 160);
}
if (indexPath.row == 0) {
cell.separatorInset.left = 1000
//cell.layer.borderWidth = 0
//cell.separatorInset = UIEdgeInsetsMake(0, 160, 0, 160);
// self.tableview.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableview.frame.width, height: 1))
}
Thank you
Separator between header and cell belongs to first cell in section.
When I used standard UITableViewHeaderFooterView and UITableViewCell I managed to hide line between header and cell via this code:
let contentView = cell.contentView
if
// this separator is subview of first UITableViewCell in section
indexPath.row == 0,
// truing to find it in subviews
let divider = cell.subviews.filter({ $0.frame.minY == 0 && $0 !== contentView }).first
{
divider.isHidden = true
}
This piece of code must be invoked in tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)
This is objective c code, this help you
http://www.iostute.com/2015/04/expandable-and-collapsable-tableview.html
For both swift and objective c
http://www.anexinet.com/blog/expandable-collapsible-uitableview-sections/
The 1st link has custom header view, so border lines won't come here.
Comment this code in viewForHeaderInSection function
// /********** Add a custom Separator with Section view *******************/
// UIView* separatorLineView = [[UIView alloc] initWithFrame:CGRectMake(15, 40, _expandableTableView.frame.size.width-15, 1)];
// separatorLineView.backgroundColor = [UIColor blackColor];
// [sectionView addSubview:separatorLineView];
See the screen shot
The closest I could solve this problem is to change UITableView's Style from "Grouped" to "Plain".
I wouldn't recommend it if you can find a better solution because now the section headers stick to the top of the screen when scrolling, which is undesirable (I believe the proper way to describe this is "the section headers float").
I have a UITableView that displays some content. When the user scrolls upward, the cells below don't always load immediately. This creates an area of white space at the bottom of the table. I would like to display a spinner in the white space and have it disappear when the content is done loading, but I'm not sure how to go about doing this. What is a good way to implement something like this in swift?
I am new to coding and iOS, please forgive me if the question is vague or the answer is obvious.
Sample Screenshot :
I think it's helpful for you..
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let lastSectionIndex = tableView.numberOfSections - 1
let lastRowIndex = tableView.numberOfRows(inSection: lastSectionIndex) - 1
if indexPath.section == lastSectionIndex && indexPath.row == lastRowIndex {
// print("this is the last cell")
let spinner = UIActivityIndicatorView(activityIndicatorStyle: .red)
spinner.startAnimating()
spinner.frame = CGRect(x: CGFloat(0), y: CGFloat(0), width: tableView.bounds.width, height: CGFloat(44))
self.tableview.tableFooterView = spinner
self.tableview.tableFooterView?.isHidden = false
}
}
tableFooterView should be hide when data load.
when above function isn't work so you can prefer this link.
Set UIActivityIndicatorView as a UITableView's footerView in viewDidLoad.
self.indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
self.indicator.hidesWhenStopped = YES;
self.indicator.frame = CGRectMake(0, 0, self.tableView.bounds.size.width, 44);
self.tableView.tableFooterView = self.indicator;
When the tableview is about to display the last row of cells and you have more data to load, then load more data.
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row == self.arrList.count-1 && self.hasMoreList == YES) {
[self loadData];
}
}
Just start animating indicator before loading and stop animating it after loading data.
- (void)loadData {
[self.indicator startAnimating];
// load data and set hasMoreData here ...
[self.indicator stopAnimating];
}
In my app, there exist a scenario where I hide the bottom TabBar by [self.tabBarController.tabBar setHidden:YES] and later add a UIView containing UIButtons in the vacated area at the bottom of the view.
The area where the TabBar was will not respond to touch events so I can't select any of the buttons in the UIView.
I've done research on here and this question has been around for awhile but the old answers don't seem to work anymore. [self setNeeds Display] and self.tabBarController.tabBar.translucent = YES, do not work anymore as you still can't press the UIButtons. On a side note, I created my UIView with UIButtons in storyboards and put a bottom constraint to the superview. Please provide an answer known to work for iOS 9 and 10.
I created a project according to question. It's work fine. Please try this.
- (void)viewDidLoad {
[super viewDidLoad];
[self.tabBarController.tabBar setHidden:YES];
UIView *view = [[UIView alloc]initWithFrame:self.tabBarController.tabBar.frame];
[self.view addSubview:view];
view.backgroundColor = [UIColor redColor];
UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100,view.frame.size.height)];
[view addSubview:btn];
[btn setTitle:#"clicked me " forState:UIControlStateNormal];
[btn addTarget:self action:#selector(btnclicked:) forControlEvents:UIControlEventTouchDown];
}
-(void)btnclicked:(UIButton *)sender{ NSLog(#"button clicked event."); }
I created a test project to check the functionality that you want.
class ViewController: UIViewController {
#IBOutlet weak var testButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
testButton.addTarget(self, action: #selector(tapped), for: .touchUpInside)
self.tabBarController?.tabBar.isHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tapped(_ sender:UIButton){
print("Tapped")
}
}
As per your requirement, i created a uiview containing a UIButton as a subview and created a outlet for the button.
As, i tab on on the button the action - tapped is triggered.
I have tableview in one viewcontroller. I have one section in that. I want to add button in footer. I have written this code but footer view is not displaying.
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
UIView *footerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
UIButton *addcharity=[UIButton buttonWithType:UIButtonTypeCustom];
[addcharity setTitle:#"Add to other" forState:UIControlStateNormal];
[addcharity addTarget:self action:#selector(addCharity:) forControlEvents:UIControlEventTouchUpInside];
addcharity.frame=CGRectMake(0, 0, 40, 30);
[footerView addSubview:addcharity];
return footerView;
}
I have also set height of footer 100 in its delegate method.
screenshots:
Initially i have 3 data. But when I search for particular data and result will be displayed in tableview at that time I have one data so at that time footer location changed. I want to to fix footer at initial place.
Edit:
As an alternative solution one can add button by adding extra cell at the end.
Per Apple's Docs you must also implement the heightForFooterInSection method, otherwise your viewForFooterInSection wouldn't do anything.
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
return 100.0f;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
if(tableView == myListTableview) //Here you can make decision
{
UIView *footerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
UIButton *addcharity=[UIButton buttonWithType:UIButtonTypeCustom];
[addcharity setTitle:#"Add to other" forState:UIControlStateNormal];
[addcharity addTarget:self action:#selector(addCharity:) forControlEvents:UIControlEventTouchUpInside];
[addcharity setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; //Set the color this is may be different for iOS 7
addcharity.frame=CGRectMake(0, 0, 130, 30); //Set some large width for your title
[footerView addSubview:addcharity];
return footerView;
}
}
- (void)addCharity:(id)sender
{
NSLog(#"add to charity");
}
Same code in swift
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 100.0
}
func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerView = UIView(frame:CGRectMake(0,0,320,40))
let loginButton = UIButton(type: .Custom)
loginButton.setTitle("LOGIN", forState: .Normal)
loginButton.addTarget(self, action: "loginAction", forControlEvents: .TouchUpInside)
loginButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
loginButton.backgroundColor = UIColor.blueColor()
loginButton.frame = CGRectMake(0, 0, 130, 30)
footerView.addSubview(loginButton)
return footerView
}
func loginAction()
{
print("Hello");
}
Be sure of three things
1- You not implementing this method
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
2- This method
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
Is a UITableViewDelegate method and not UITableViewDataSource, Check if delegate of the tableview is set with the controller
3- Be sure you are implementing this method
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
Finally, If everything is correct and still not working then You can just add the view in "tableFooterView" property of the table to be the footer of the whole table and not only the section
I want to customize UITableView header for each section. So far, I've implemented
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
this UITabelViewDelegate method. What I want to do is to get current header for each section and just add UILabel as a subview.
So far, I'm not able to accomplish that. Because, I couldn't find anything to get default section header. First question,is there any way to get default section header?
If it's not possible, I need to create a container view which is a UIView but,this time I need to set default background color,shadow color etc. Because, if you look carefully into section's header, it's already customized.
How can I get these default values for each section header?
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;
}
The selected answer using tableView :viewForHeaderInSection: is correct.
Just to share a tip here.
If you are using storyboard/xib, then you could create another prototype cell and use it for your "section cell". The code to configure the header is similar to how you configure for row cells.
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
static NSString *HeaderCellIdentifier = #"Header";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HeaderCellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:HeaderCellIdentifier];
}
// Configure the cell title etc
[self configureHeaderCell:cell inSection:section];
return cell;
}
Swift version of Lochana Tejas answer:
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 18))
let label = UILabel(frame: CGRectMake(10, 5, tableView.frame.size.width, 18))
label.font = UIFont.systemFontOfSize(14)
label.text = list.objectAtIndex(indexPath.row) as! String
view.addSubview(label)
view.backgroundColor = UIColor.grayColor() // Set your background color
return view
}
If you use default header view you can only change the text on it with
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
For Swift:
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
If you want to customize the view you need to create a new one your self.
why not use UITableViewHeaderFooterView?
If headerInSection isn't show, can try this.
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 45;
}
This returns a height for the header of a given section.
Swift 3 version of lochana and estemendoza answers:
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x:0, y:0, width:tableView.frame.size.width, height:18))
let label = UILabel(frame: CGRect(x:10, y:5, width:tableView.frame.size.width, height:18))
label.font = UIFont.systemFont(ofSize: 14)
label.text = "This is a test";
view.addSubview(label);
view.backgroundColor = UIColor.gray;
return view
}
Also, be advised that you ALSO have to implement:
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 100;
}
The other answers do a good job of recreating the default header view, but don't actually answer your main question:
is there any way to get default section header ?
There is a way - just implement tableView:willDisplayHeaderView:forSection: in your delegate. The default header view will be passed into the second parameter, and from there you can cast it to a UITableViewHeaderFooterView and then add/change subviews as you wish.
Obj-C
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
// Do whatever with the header view... e.g.
// headerView.textLabel.textColor = [UIColor whiteColor]
}
Swift
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
{
let headerView = view as! UITableViewHeaderFooterView
// Do whatever with the header view... e.g.
// headerView.textLabel?.textColor = UIColor.white
}
Try this......
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
{
// Background view is at index 0, content view at index 1
if let bgView = view.subviews[0] as? UIView
{
// do your stuff
}
view.layer.borderColor = UIColor.magentaColor().CGColor
view.layer.borderWidth = 1
}
This is the easiest solution possible. The following code can be used directly for creating a custom section header.
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
SectionHeaderTableViewCell *headerView = [tableView dequeueReusableCellWithIdentifier:#"sectionHeader"];
//For creating a drop menu of rows from the section
//==THIS IS JUST AN EXAMPLE. YOU CAN REMOVE THIS IF-ELSE.==
if (![self.sectionCollapsedArray[section] boolValue])
{
headerView.imageView.image = [UIImage imageNamed:#"up_icon"];
}
else
{
headerView.imageView.image = [UIImage imageNamed:#"drop_icon"];
}
//For button action inside the custom cell
headerView.dropButton.tag = section;
[headerView.dropButton addTarget:self action:#selector(sectionTapped:) forControlEvents:UIControlEventTouchUpInside];
//For removing long touch gestures.
for (UIGestureRecognizer *recognizer in headerView.contentView.gestureRecognizers)
{
[headerView.contentView removeGestureRecognizer:recognizer];
[headerView removeGestureRecognizer:recognizer];
}
return headerView.contentView;
}
NOTE: SectionHeaderTableViewCell is a custom UITableViewCell created in Storyboard.
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
//put your values, this is part of my code
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 30.0f)];
[view setBackgroundColor:[UIColor redColor]];
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 5, 150, 20)];
[lbl setFont:[UIFont systemFontOfSize:18]];
[lbl setTextColor:[UIColor blueColor]];
[view addSubview:lbl];
[lbl setText:[NSString stringWithFormat:#"Section: %ld",(long)section]];
return view;
}
Full 2019 example to copy and paste
First set "Grouped" on storyboard: it has to happen at init time, you can't really set it later, so it's easier to remember to do it on storyboard:
Next,
Must implement heightForHeaderInSection due to Apple bug.
func tableView(_ tableView: UITableView,
heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat(70.0)
}
There is still an Apple bug - for ten years now - where it simply won't show the first header (i.e., index 0) if you don't have heightForHeaderInSection call.
So, tableView.sectionHeaderHeight = 70 simply doesn't work, it's broken.
Setting a frame achieves nothing:
In viewForHeaderInSection simply create a UIView().
It is pointless / achieves nothing if you UIView(frame ...) since iOS simply sets the size of the view as determined by the table.
So the first line of viewForHeaderInSection will be simply let view = UIView() and that is the view you return.
func tableView(_ tableView: UITableView,
viewForHeaderInSection section: Int) -> UIView? {
let view = UIView()
let l = UILabel()
view.addSubview(l)
l.bindEdgesToSuperview()
l.backgroundColor = .systemOrange
l.font = UIFont.systemFont(ofSize: 15)
l.textColor = .yourClientsFavoriteColor
switch section {
case 0:
l.text = "First section on screen"
case 1:
l.text = "Here's the second section"
default:
l.text = ""
}
return view
}
That's it - anything else is a time waste.
Another "fussy" Apple issue.
The convenience extension used above is:
extension UIView {
// incredibly useful:
func bindEdgesToSuperview() {
guard let s = superview else {
preconditionFailure("`superview` nil in bindEdgesToSuperview")
}
translatesAutoresizingMaskIntoConstraints = false
leadingAnchor.constraint(equalTo: s.leadingAnchor).isActive = true
trailingAnchor.constraint(equalTo: s.trailingAnchor).isActive = true
topAnchor.constraint(equalTo: s.topAnchor).isActive = true
bottomAnchor.constraint(equalTo: s.bottomAnchor).isActive = true
}
}
If I were you, I would make a method which returns an UIView given a NSString to contain. For example
+ (UIView *) sectionViewWithTitle:(NSString *)title;
In the implementation of this method create a UIView, add a UILabel to it with the properties you want to set, and of course set its title to the given one.
#samwize's solution in Swift (so upvote him!). Brilliant using same recycling mechanism also for header/footer sections:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let settingsHeaderSectionCell:SettingsHeaderSectionCell = self.dequeueReusableCell(withIdentifier: "SettingsHeaderSectionCell") as! SettingsHeaderSectionCell
return settingsHeaderSectionCell
}
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
if([view isKindOfClass:[UITableViewHeaderFooterView class]]){
UITableViewHeaderFooterView *headerView = view;
[[headerView textLabel] setTextColor:[UIColor colorWithHexString:#"666666"]];
[[headerView textLabel] setFont:[UIFont fontWithName:#"fontname" size:10]];
}
}
If you want to change the font of the textLabel in your section header you want to do it in willDisplayHeaderView. To set the text you can do it in viewForHeaderInSection or titleForHeaderInSection. Good luck!
Magically add Table View Header in swift
Recently I tried this.
I needed one and only one header in the whole UITableView.
Like I wanted a UIImageView on the top of the TableView. So I added a UIImageView on top of the UITableViewCell and automatically it was added as a tableViewHeader. Now I connect the ImageView to the ViewController and added the Image.
I was confused because I did something like this for the first time. So to clear my confusion open the xml format of the MainStoryBoard and found the Image View was added as a header.
It worked for me. Thanks xCode and swift.
call this delegate method
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return #"Some Title";
}
this will give a chance to automatically add a default header with dynamic title .
You may use reusable and customizable header / footer .
https://github.com/sourov2008/UITableViewCustomHeaderFooterSection
swif 4.2
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let header = view as? UITableViewHeaderFooterView else { return }
header.textLabel?.textAlignment = .center // for all sections
switch section {
case 1: //only section No.1
header.textLabel?.textColor = .black
case 3: //only section No.3
header.textLabel?.textColor = .red
default: //
header.textLabel?.textColor = .yellow
}
}
besides to titleForHeaderInSection, you can simply change view of header, footer.
check my comment here: Change UITable section backgroundColor without loosing section Title
If you just want to add title to the tableView header dont add a view. In swift 3.x the code goes like this:
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
var lblStr = ""
if section == 0 {
lblStr = "Some String 1"
}
else if section == 1{
lblStr = "Some String 2"
}
else{
lblStr = "Some String 3"
}
return lblStr
}
You may implement an array to fetch the title for the headers.
Going back to the original question (4 years later), rather than rebuilding your own section header, iOS can simply call you (with willDisplayHeaderView:forSection:) right after it's built the default one. For example, I wanted to add a graph button on right edge of section header:
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
UITableViewHeaderFooterView * header = (UITableViewHeaderFooterView *) view;
if (header.contentView.subviews.count > 0) return; //in case of reuse
CGFloat rightEdge = CGRectGetMaxX(header.contentView.bounds);
UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(rightEdge - 44, 0, 44, CGRectGetMaxY(header.contentView.bounds))];
[button setBackgroundImage:[UIImage imageNamed:#"graphIcon"] forState:UIControlStateNormal];
[button addTarget:self action:#selector(graphButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:button];
}
Use tableView: willDisplayHeaderView: to customize the view when it is about to be displayed.
This gives you the advantage of being able to take the view that was already created for the header view and extend it, instead of having to recreate the whole header view yourself.
Here is an example that colors the header section based on a BOOL and adds a detail text element to the header.
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
// view.tintColor = [UIColor colorWithWhite:0.825 alpha:1.0]; // gray
// view.tintColor = [UIColor colorWithRed:0.825 green:0.725 blue:0.725 alpha:1.0]; // reddish
// view.tintColor = [UIColor colorWithRed:0.925 green:0.725 blue:0.725 alpha:1.0]; // pink
// Conditionally tint the header view
BOOL isMyThingOnOrOff = [self isMyThingOnOrOff];
if (isMyThingOnOrOff) {
view.tintColor = [UIColor colorWithRed:0.725 green:0.925 blue:0.725 alpha:1.0];
} else {
view.tintColor = [UIColor colorWithRed:0.925 green:0.725 blue:0.725 alpha:1.0];
}
/* Add a detail text label (which has its own view to the section header… */
CGFloat xOrigin = 100; // arbitrary
CGFloat hInset = 20;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(xOrigin + hInset, 5, tableView.frame.size.width - xOrigin - (hInset * 2), 22)];
label.textAlignment = NSTextAlignmentRight;
[label setFont:[UIFont fontWithName:#"Helvetica-Bold" size:14.0]
label.text = #"Hi. I'm the detail text";
[view addSubview:label];
}
Swift 4.2
In Swift 4.2 the name of table is a little changed.
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 18))
let label = UILabel(frame: CGRect(x: 10, y: 5, width: tableView.frame.size.width, height: 18))
label.font = UIFont.systemFont(ofSize: 14)
label.text = list.objectAtIndex(section) as! String
view.addSubview(label)
view.backgroundColor = UIColor.gray // Set your background color
return view
}
Code for Swift 5
We can implement this by using two tableView delegate functions:
1] We can give custom height for the section:
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 49
}
2] Then we can create custom header:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let sectionV = UIView.init(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 48) )
let titleLbl = UILabel.init(frame: CGRect(x: 25, y: 24, width: tableView.frame.width-150, height: 20) )
let viewAllBtn = UIButton.init(frame: CGRect(x: tableView.frame.width-150, y: 15, width: self.view.frame.width - titleLbl.frame.width, height: 45))
viewAllBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
viewAllBtn.setTitle("View All", for: .normal)
viewAllBtn.setTitleColor(.systemBlue, for: .normal)
viewAllBtn.tag = section
titleLbl.text = dashboardTempData.data?[section].title
titleLbl.font = UIFont.systemFont(ofSize: 21, weight: UIFont.Weight.medium)
sectionV.backgroundColor = .systemBackground
sectionV.addSubview(titleLbl)
sectionV.addSubview(viewAllBtn)
sectionV.bringSubviewToFront(viewAllBtn)
return sectionV
}
It will create a Label and Button with a section header height of 49