Auto-Resize UITableView Headers on Rotate (Mostly on iPad) - ios

I feel like this is going to be a simple answer revolving around AutoResizingMasks, but I can't seem to wrap my head around this topic.
I've got an iPad app that shows 2 UITableViews side-by-side. When I rotate from Portrait to Landscape and back, the cells in the UITableView resize perfectly, on-the-fly, while the rotation is occurring. I'm using UITableViewCellStyleSubtitle UITableViewCells (not subclassed for now), and I've set the UITableView up in IB to anchor to the top, left and bottom edges (for the left UITableView) and to have a flexible width.
I'm supplying my own UIView object for
- (UIView *)tableView:(UITableView *)tableView
viewForHeaderInSection:(NSInteger)section
Here's what I've got so far (called as a class method from another class):
+ (UIView *)headerForTableView:(UITableView *)tv
{
// The view to return
UIView *headerView = [[UIView alloc]
initWithFrame:CGRectMake(0, 0, [tv frame].size.width, someHeight)];
[headerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleRightMargin];
// Other layout logic... doesn't seem to be the culprit
// Return the HeaderView
return headerView;
}
So, in either orientation, everything loads up just like I want. After rotation, if I manually call reloadData or wait until my app triggers it, or scroll the UITableView, the headerViews will resize and show themselves properly. What I can't figure out is how to get the AutoResizeMask property set properly so that the header will resize just like the cells.

Not a very good fix. But works :
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
[super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration];
[mTableView reloadData];
}

I faced the same issue recently. The trick was to use a custom view as the headerView of the table. Overriding layoutSubviews allowed me to control the layout at will. Below is an example.
#import "TableSectionHeader.h"
#implementation TableSectionHeader
- (id)initWithFrame:(CGRect)frame title:(NSString *)title
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor clearColor];
// Initialization code
headerLabel = [[UILabel alloc] initWithFrame:frame];
headerLabel.text = title;
headerLabel.textColor = [UIColor blackColor];
headerLabel.font = [UIFont boldSystemFontOfSize:17];
headerLabel.backgroundColor = [UIColor clearColor];
[self addSubview:headerLabel];
}
return self;
}
-(void)dealloc {
[headerLabel release];
[super dealloc];
}
-(void)layoutSubviews {
[super layoutSubviews];
NSInteger xOffset = ((55.0f / 768.0f) * self.bounds.size.width);
if (xOffset > 55.0f) {
xOffset = 55.0f;
}
headerLabel.frame = CGRectMake(xOffset, 15, self.bounds.size.width - xOffset * 2, 20);
}
+(UIView *) tableSectionHeaderWithText:(NSString *) text bounds:(CGRect)bounds {
TableSectionHeader *header = [[[TableSectionHeader alloc] initWithFrame:CGRectMake(0, 0, bounds.size.width, 40) title:text] autorelease];
return header;
}
+(CGFloat) tableSectionHeaderHeight {
return 40.0;
}
#end

I'd love to get a real answer to this, but for now, I've just re-worked my UITableView so that my "headers" are just cells inside the table. Resizing has no issues that way.

I have created UIView subclass where I've used visual constraints to stick the subview to the sides of the screen. And rotation is all fine.
class MLFlexibleView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(self.segmentedControl)
self.setUpConstraints()
}
func setUpConstraints() {
let views = ["view" : self.segmentedControl]
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:|-7-[view]-7-|", options: [], metrics: nil, views: views))
NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|-15-[view]-15-|", options: [], metrics: nil, views: views))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let segmentedControl:UISegmentedControl = {
let segmentedControl = UISegmentedControl(items: ["Searches".localized, "Adverts".localized])
segmentedControl.selectedSegmentIndex = 0
segmentedControl.tintColor = UIColor.white
segmentedControl.translatesAutoresizingMaskIntoConstraints = false
return segmentedControl
}()
}

Related

iOS: the background color of the header of my TableView is not changing anymore in iOS13

My TableView's header is not displaying well in iOS13. No matter what color I put, it always displays a light gray now...
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{ //Section color & style
UITableViewHeaderFooterView *v = (UITableViewHeaderFooterView *)view;
v.backgroundView.alpha = 1;
v.textLabel.textColor = sectionColor;
v.textLabel.font = sectionFont;
v.textLabel.numberOfLines = 1;
v.textLabel.minimumScaleFactor = 0.5;
v.textLabel.adjustsFontSizeToFitWidth = YES;
v.backgroundView.backgroundColor = [UIColor blueColor];
}
iOS12:
iOS13:
It is strange because when I put a stop in the debugger in step by step, it displays me the good image in iOS13, but not in the app:
Any suggestions, thanks in advance ?
I was noticing the same thing in one of my apps.
Then saw a log message in the console:
Setting the background color on UITableViewHeaderFooterView has been
deprecated. Please set a custom UIView with your desired background
color to the backgroundView property instead.
Setting a custom UIView with the desired background color as the backgroundView of the UITableViewHeaderFooterView solved the problem.
Code sample
class SomeHeaderView: UITableViewHeaderFooterView {
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
configure()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func configure() {
let backgroundView = UIView(frame: .zero)
backgroundView.backgroundColor = .blue
self.backgroundView = backgroundView
}
}
This works for me.
v.contentView.backgroundColor = .blue
instead of
v.backgroundView.backgroundColor = .blue
Try to add overlay view and change this color for this view.
UIView *coloredView = [[UIView alloc] init];
coloredView.backgroundColor = [UIColor blueColor];
[v addSubview:coloredView];
[[coloredView.leadingAnchor constraintEqualToAnchor:v.leadingAnchor constant:0] setActive:YES];
[[coloredView.trailingAnchor constraintEqualToAnchor:v.trailingAnchor constant:0] setActive:YES];
[[coloredView.topAnchor constraintEqualToAnchor:v.topAnchor constant:0] setActive:YES];
[[coloredView.bottomAnchor constraintEqualToAnchor:v.bottomAnchor constant:0] setActive:YES];

Add subview in UITabBar

I want to customise UITabBar by subclassing it I am not able to get the UITabBar frame here is my code
in home_tabbar.h
#import <UIKit/UIKit.h>
#interface home_tabbar : UITabBar
-(void) changeFrame;
#end
in home_tabbar.m
#import "home_tabbar.h"
#implementation home_tabbar
- (void)viewDidAppear:(BOOL)animated {
[self changeFrame];
}
- (void)changeFrame
{
CGRect frame = self.viewForLastBaselineLayout.frame;
NSLog(#"Frame x= %f y=%f width=%f height=%f",frame.origin.x,frame.origin.y,frame.size.width,frame.size.height);
}
#end
You can do it like this…
Subclass UITabBarController, and add a property for the view you want to add, a button in this case…
#property (strong, nonatomic) IBOutlet UIButton *videoButton;
Configure in viewDidLoad…
- (void)viewDidLoad
{
[super viewDidLoad];
self.videoButton.layer.cornerRadius = 4.0;
self.videoButton.backgroundColor = [UIColor yellowColor];
self.videoButton.clipsToBounds = YES;
[self.tabBar addSubview: self.videoButton];
}
then in viewDidLayoutSubviews…
- (void) viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
// Only need to do this once if the orientation is fixed
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
self.videoButton.center = (CGPoint){CGRectGetMidX(self.tabBar.bounds), CGRectGetMidY(self.tabBar.bounds)};
});
// system moves subviews behind tab bar buttons, this fixes
[self.tabBar bringSubviewToFront: self.videoButton];
}
I have created a class to customize the UITabBar. In my case I had to add a background image and update the height.
Here my code:
class DDTabBar: UITabBar {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let backgroundImage = UIImageView(image: UIImage(named: "TabBar_Background"))
backgroundImage.contentMode = UIViewContentMode.scaleAspectFill
var tabFrame = self.bounds
tabFrame.size.height = 75
backgroundImage.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tabFrame.origin.y = self.bounds.size.height - 75
backgroundImage.frame = tabFrame
self.insertSubview(backgroundImage, at: 0)
}
}

tableHeaderView on top of first cell

I'm trying to create a tableview programmatically that has a search bar in the tableHeaderView. For some reason the search bar appears on top of the first cell.
I'm using Masonry to build constraints.
Can someone point me to what i'm doing wrong.
- (void)setupViews {
...
self.tableView = [[UITableView alloc] initWithFrame:CGRectZero];
[self.view addSubview:self.tableView];
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
self.tableView.tableHeaderView = self.searchBar;
...
}
- (void)updateViewConstraints {
[self.searchBar mas_updateConstraints:^(MASConstraintMaker *make) {
make.width.equalTo(self.view);
make.height.equalTo(#(44));
}];
[self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
make.self.top.equalTo(self.view);
make.self.bottom.equalTo(self.toolbar.mas_top);
make.width.equalTo(self.view);
}];
...
}
You can see here that the header is at the same level as the cells.
Thanks for your help, I found a gist on GitHub which talked about changing the size of tableViewHeader using AutoLayout:
https://gist.github.com/andreacremaschi/833829c80367d751cb83
- (void) sizeHeaderToFit {
UIView *headerView = self.tableHeaderView;
[headerView setNeedsLayout];
[headerView layoutIfNeeded];
CGFloat height = [headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
headerView.frame = ({
CGRect headerFrame = headerView.frame;
headerFrame.size.height = height;
headerFrame;
});
self.tableHeaderView = headerView;
}
If I call this method during updateViewConstraints then it works.
However, I don't fully understand it.
Using Extension in Swift 3.0
extension UITableView {
func setTableHeaderView(headerView: UIView?) {
// prepare the headerView for constraints
headerView?.translatesAutoresizingMaskIntoConstraints = false
// set the headerView
tableHeaderView = headerView
// check if the passed view is nil
guard let headerView = headerView else { return }
// check if the tableHeaderView superview view is nil just to avoid
// to use the force unwrapping later. In case it fail something really
// wrong happened
guard let tableHeaderViewSuperview = tableHeaderView?.superview else {
assertionFailure("This should not be reached!")
return
}
// force updated layout
headerView.setNeedsLayout()
headerView.layoutIfNeeded()
// set tableHeaderView width
tableHeaderViewSuperview.addConstraint(headerView.widthAnchor.constraint(equalTo: tableHeaderViewSuperview.widthAnchor, multiplier: 1.0))
// set tableHeaderView height
let height = headerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
tableHeaderViewSuperview.addConstraint(headerView.heightAnchor.constraint(equalToConstant: height))
}
func setTableFooterView(footerView: UIView?) {
// prepare the headerView for constraints
headerView?.translatesAutoresizingMaskIntoConstraints = false
// set the footerView
tableFooterView = footerView
// check if the passed view is nil
guard let footerView = footerView else { return }
// check if the tableFooterView superview view is nil just to avoid
// to use the force unwrapping later. In case it fail something really
// wrong happened
guard let tableFooterViewSuperview = tableFooterView?.superview else {
assertionFailure("This should not be reached!")
return
}
// force updated layout
footerView.setNeedsLayout()
footerView.layoutIfNeeded()
// set tableFooterView width
tableFooterViewSuperview.addConstraint(footerView.widthAnchor.constraint(equalTo: tableFooterViewSuperview.widthAnchor, multiplier: 1.0))
// set tableFooterView height
let height = footerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
tableFooterViewSuperview.addConstraint(footerView.heightAnchor.constraint(equalToConstant: height))
}
}
I think the problem is because you are using autolayout and setting frames to views manually, replace this code:
self.tableView = [[UITableView alloc] initWithFrame:CGRectZero];
[self.view addSubview:self.tableView];
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectZero];
self.tableView.tableHeaderView = self.searchBar;
with something like this:
self.tableView = [UITableView new];
self.tableView.translatesAutoresizingMasksIntoConstraints = NO;
[self.view addSubview:self.tableView];
self.searchBar = [UISearchBar new];
self.searchBar.translatesAutoresizingMasksIntoConstraints = NO;
self.tableView.tableHeaderView = self.searchBar;
It may not work, because maybe searchBar's frame needs to be set manually without constraints.
Here issue regarding space between table view Header and table view Cell. You can handle using Attribute Inspector. Please review that.
- select UITableView
- Under attribute inspector -> Scroll view size -> Content insets, set Top = 44 (or whichever is your nav bar height).
Or you can Handle it programmatically.
- (void)viewDidLoad {
UIEdgeInsets inset = UIEdgeInsetsMake(20, 0, 0, 0);
self.tableView.contentInset = inset;
}

Using autolayout in a tableHeaderView

I have a UIView subclass that contains a multi-line UILabel. This view uses autolayout.
I would like to set this view as the tableHeaderView of a UITableView (not a section header). The height of this header will depend on the text of the label, which in turn depends on the width of the device. The sort of scenario autolayout should be great at.
I have found and attempted many many solutions to get this working, but to no avail. Some of the things I've tried:
setting a preferredMaxLayoutWidth on each label during layoutSubviews
defining an intrinsicContentSize
attempting to figure out the required size for the view and setting the tableHeaderView's frame manually.
adding a width constraint to the view when the header is set
a bunch of other things
Some of the various failures I've encountered:
label extends beyond the width of the view, doesn't wrap
frame's height is 0
app crashes with exception Auto Layout still required after executing -layoutSubviews
The solution (or solutions, if necessary) should work for both iOS 7 and iOS 8. Note that all of this is being done programmatically. I've set up a small sample project in case you want to hack on it to see the issue. I've reset my efforts to the following start point:
SCAMessageView *header = [[SCAMessageView alloc] init];
header.titleLabel.text = #"Warning";
header.subtitleLabel.text = #"This is a message with enough text to span multiple lines. This text is set at runtime and might be short or long.";
self.tableView.tableHeaderView = header;
What am I missing?
My own best answer so far involves setting the tableHeaderView once and forcing a layout pass. This allows a required size to be measured, which I then use to set the frame of the header. And, as is common with tableHeaderViews, I have to again set it a second time to apply the change.
- (void)viewDidLoad
{
[super viewDidLoad];
self.header = [[SCAMessageView alloc] init];
self.header.titleLabel.text = #"Warning";
self.header.subtitleLabel.text = #"This is a message with enough text to span multiple lines. This text is set at runtime and might be short or long.";
//set the tableHeaderView so that the required height can be determined
self.tableView.tableHeaderView = self.header;
[self.header setNeedsLayout];
[self.header layoutIfNeeded];
CGFloat height = [self.header systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
//update the header's frame and set it again
CGRect headerFrame = self.header.frame;
headerFrame.size.height = height;
self.header.frame = headerFrame;
self.tableView.tableHeaderView = self.header;
}
For multiline labels, this also relies on the custom view (the message view in this case) setting the preferredMaxLayoutWidth of each:
- (void)layoutSubviews
{
[super layoutSubviews];
self.titleLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.titleLabel.frame);
self.subtitleLabel.preferredMaxLayoutWidth = CGRectGetWidth(self.subtitleLabel.frame);
}
Update January 2015
Unfortunately this still seems necessary. Here is a swift version of the layout process:
tableView.tableHeaderView = header
header.setNeedsLayout()
header.layoutIfNeeded()
let height = header.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
var frame = header.frame
frame.size.height = height
header.frame = frame
tableView.tableHeaderView = header
I've found it useful to move this into an extension on UITableView:
extension UITableView {
//set the tableHeaderView so that the required height can be determined, update the header's frame and set it again
func setAndLayoutTableHeaderView(header: UIView) {
self.tableHeaderView = header
header.setNeedsLayout()
header.layoutIfNeeded()
let height = header.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
var frame = header.frame
frame.size.height = height
header.frame = frame
self.tableHeaderView = header
}
}
Usage:
let header = SCAMessageView()
header.titleLabel.text = "Warning"
header.subtitleLabel.text = "Warning message here."
tableView.setAndLayoutTableHeaderView(header)
For anyone still looking for a solution, this is for Swift 3 & iOS 9+. Here is one using only AutoLayout. It also updates correctly on device rotation.
extension UITableView {
// 1.
func setTableHeaderView(headerView: UIView) {
headerView.translatesAutoresizingMaskIntoConstraints = false
self.tableHeaderView = headerView
// ** Must setup AutoLayout after set tableHeaderView.
headerView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
headerView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
headerView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
}
// 2.
func shouldUpdateHeaderViewFrame() -> Bool {
guard let headerView = self.tableHeaderView else { return false }
let oldSize = headerView.bounds.size
// Update the size
headerView.layoutIfNeeded()
let newSize = headerView.bounds.size
return oldSize != newSize
}
}
To use:
override func viewDidLoad() {
...
// 1.
self.tableView.setTableHeaderView(headerView: customView)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// 2. Reflect the latest size in tableHeaderView
if self.tableView.shouldUpdateHeaderViewFrame() {
// **This is where table view's content (tableHeaderView, section headers, cells)
// frames are updated to account for the new table header size.
self.tableView.beginUpdates()
self.tableView.endUpdates()
}
}
The gist is that you should let tableView manage the frame of tableHeaderView the same way as table view cells. This is done through tableView's beginUpdates/endUpdates.
The thing is that tableView doesn't care about AutoLayout when it updates the children frames. It uses the current tableHeaderView's size to determine where the first cell/section header should be.
1) Add a width constraint so that the tableHeaderView uses this width whenever we call layoutIfNeeded(). Also add centerX and top constraints to position it correctly relative to the tableView.
2) To let the tableView knows about the latest size of tableHeaderView, e.g., when the device is rotated, in viewDidLayoutSubviews we can call layoutIfNeeded() on tableHeaderView. Then, if the size is changed, call beginUpdates/endUpdates.
Note that I don't include beginUpdates/endUpdates in one function, as we might want to defer the call to later.
Check out a sample project
The following UITableView extension solves all common problems of autolayouting and positioning of the tableHeaderView without frame-use legacy:
#implementation UITableView (AMHeaderView)
- (void)am_insertHeaderView:(UIView *)headerView
{
self.tableHeaderView = headerView;
NSLayoutConstraint *constraint =
[NSLayoutConstraint constraintWithItem: headerView
attribute: NSLayoutAttributeWidth
relatedBy: NSLayoutRelationEqual
toItem: headerView.superview
attribute: NSLayoutAttributeWidth
multiplier: 1.0
constant: 0.0];
[headerView.superview addConstraint:constraint];
[headerView layoutIfNeeded];
NSArray *constraints = headerView.constraints;
[headerView removeConstraints:constraints];
UIView *layoutView = [UIView new];
layoutView.translatesAutoresizingMaskIntoConstraints = NO;
[headerView insertSubview:layoutView atIndex:0];
[headerView addConstraints: [NSLayoutConstraint constraintsWithVisualFormat:#"|[view]|" options:0 metrics:nil views:#{#"view": layoutView}]];
[headerView addConstraints: [NSLayoutConstraint constraintsWithVisualFormat:#"V:|[view]|" options:0 metrics:nil views:#{#"view": layoutView}]];
[headerView addConstraints:constraints];
self.tableHeaderView = headerView;
[headerView layoutIfNeeded];
}
#end
Explanation of the "strange" steps:
At first we tie the headerView width to the tableView width: it helps as under rotations and prevent from deep left shift of X-centered subviews of the headerView.
(the Magic!) We insert fake layoutView in the headerView:
At this moment we STRONGLY need to remove all headerView constraints,
expand the layoutView to the headerView and then restore initial headerView
constraints. It happens that order of constraints has some sense!
In the way we get correct headerView height auto calculation and also correct
X-centralization for all headerView subviews.
Then we only need to re-layout headerView again to obtain correct tableView
height calculation and headerView positioning above sections without
intersecting.
P.S. It works for iOS8 also. It is impossible to comment out any code string here in common case.
Some of the answers here helped me get very close to what I needed. But I encountered conflicts with the constraint "UIView-Encapsulated-Layout-Width" which is set by the system, when rotating the device back-and-forth between portrait and landscape. My solution below is largely based on this gist by marcoarment (credit to him): https://gist.github.com/marcoarment/1105553afba6b4900c10. The solution does not rely on the header view containing a UILabel. There are 3 parts:
A function defined in an extension to UITableView.
Call the function from the view controller's viewWillAppear().
Call the function from the view controller's viewWillTransition() in order to handle device rotation.
UITableView extension
func rr_layoutTableHeaderView(width:CGFloat) {
// remove headerView from tableHeaderView:
guard let headerView = self.tableHeaderView else { return }
headerView.removeFromSuperview()
self.tableHeaderView = nil
// create new superview for headerView (so that autolayout can work):
let temporaryContainer = UIView(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
temporaryContainer.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(temporaryContainer)
temporaryContainer.addSubview(headerView)
// set width constraint on the headerView and calculate the right size (in particular the height):
headerView.translatesAutoresizingMaskIntoConstraints = false
let temporaryWidthConstraint = NSLayoutConstraint(item: headerView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: width)
temporaryWidthConstraint.priority = 999 // necessary to avoid conflict with "UIView-Encapsulated-Layout-Width"
headerView.addConstraint(temporaryWidthConstraint)
headerView.frame.size = headerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
// remove the temporary constraint:
headerView.removeConstraint(temporaryWidthConstraint)
headerView.translatesAutoresizingMaskIntoConstraints = true
// put the headerView back into the tableHeaderView:
headerView.removeFromSuperview()
temporaryContainer.removeFromSuperview()
self.tableHeaderView = headerView
}
Use in UITableViewController
override func viewDidLoad() {
super.viewDidLoad()
// build the header view using autolayout:
let button = UIButton()
let label = UILabel()
button.setTitle("Tap here", for: .normal)
label.text = "The text in this header will span multiple lines if necessary"
label.numberOfLines = 0
let headerView = UIStackView(arrangedSubviews: [button, label])
headerView.axis = .horizontal
// assign the header view:
self.tableView.tableHeaderView = headerView
// continue with other things...
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tableView.rr_layoutTableHeaderView(width: view.frame.width)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
self.tableView.rr_layoutTableHeaderView(width: size.width)
}
This should do the trick for a headerView or a footerView for the UITableView using AutoLayout.
extension UITableView {
var tableHeaderViewWithAutolayout: UIView? {
set (view) {
tableHeaderView = view
if let view = view {
lowerPriorities(view)
view.frameSize = view.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
tableHeaderView = view
}
}
get {
return tableHeaderView
}
}
var tableFooterViewWithAutolayout: UIView? {
set (view) {
tableFooterView = view
if let view = view {
lowerPriorities(view)
view.frameSize = view.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
tableFooterView = view
}
}
get {
return tableFooterView
}
}
fileprivate func lowerPriorities(_ view: UIView) {
for cons in view.constraints {
if cons.priority.rawValue == 1000 {
cons.priority = UILayoutPriority(rawValue: 999)
}
for v in view.subviews {
lowerPriorities(v)
}
}
}
}
Using Extension in Swift 3.0
extension UITableView {
func setTableHeaderView(headerView: UIView?) {
// set the headerView
tableHeaderView = headerView
// check if the passed view is nil
guard let headerView = headerView else { return }
// check if the tableHeaderView superview view is nil just to avoid
// to use the force unwrapping later. In case it fail something really
// wrong happened
guard let tableHeaderViewSuperview = tableHeaderView?.superview else {
assertionFailure("This should not be reached!")
return
}
// force updated layout
headerView.setNeedsLayout()
headerView.layoutIfNeeded()
// set tableHeaderView width
tableHeaderViewSuperview.addConstraint(headerView.widthAnchor.constraint(equalTo: tableHeaderViewSuperview.widthAnchor, multiplier: 1.0))
// set tableHeaderView height
let height = headerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
tableHeaderViewSuperview.addConstraint(headerView.heightAnchor.constraint(equalToConstant: height))
}
func setTableFooterView(footerView: UIView?) {
// set the footerView
tableFooterView = footerView
// check if the passed view is nil
guard let footerView = footerView else { return }
// check if the tableFooterView superview view is nil just to avoid
// to use the force unwrapping later. In case it fail something really
// wrong happened
guard let tableFooterViewSuperview = tableFooterView?.superview else {
assertionFailure("This should not be reached!")
return
}
// force updated layout
footerView.setNeedsLayout()
footerView.layoutIfNeeded()
// set tableFooterView width
tableFooterViewSuperview.addConstraint(footerView.widthAnchor.constraint(equalTo: tableFooterViewSuperview.widthAnchor, multiplier: 1.0))
// set tableFooterView height
let height = footerView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
tableFooterViewSuperview.addConstraint(footerView.heightAnchor.constraint(equalToConstant: height))
}
}
Your constraints were just a little off. Take a look at this and let me know if you have any questions. For some reason I had difficulty getting the background of the view to stay red? So I created a filler view that fills the gap created by having a titleLabel and subtitleLabel height that is greater than the height of the imageView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
self.backgroundColor = [UIColor redColor];
self.imageView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:#"Exclamation"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]];
self.imageView.tintColor = [UIColor whiteColor];
self.imageView.translatesAutoresizingMaskIntoConstraints = NO;
self.imageView.backgroundColor = [UIColor redColor];
[self addSubview:self.imageView];
[self.imageView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self);
make.width.height.equalTo(#40);
make.top.equalTo(self).offset(0);
}];
self.titleLabel = [[UILabel alloc] init];
self.titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
self.titleLabel.font = [UIFont systemFontOfSize:14];
self.titleLabel.textColor = [UIColor whiteColor];
self.titleLabel.backgroundColor = [UIColor redColor];
[self addSubview:self.titleLabel];
[self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self).offset(0);
make.left.equalTo(self.imageView.mas_right).offset(0);
make.right.equalTo(self).offset(-10);
make.height.equalTo(#15);
}];
self.subtitleLabel = [[UILabel alloc] init];
self.subtitleLabel.translatesAutoresizingMaskIntoConstraints = NO;
self.subtitleLabel.font = [UIFont systemFontOfSize:13];
self.subtitleLabel.textColor = [UIColor whiteColor];
self.subtitleLabel.numberOfLines = 0;
self.subtitleLabel.backgroundColor = [UIColor redColor];
[self addSubview:self.subtitleLabel];
[self.subtitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.titleLabel.mas_bottom);
make.left.equalTo(self.imageView.mas_right);
make.right.equalTo(self).offset(-10);
}];
UIView *fillerView = [[UIView alloc] init];
fillerView.backgroundColor = [UIColor redColor];
[self addSubview:fillerView];
[fillerView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.imageView.mas_bottom);
make.bottom.equalTo(self.subtitleLabel.mas_bottom);
make.left.equalTo(self);
make.right.equalTo(self.subtitleLabel.mas_left);
}];
}
return self;
}
I'll add my 2 cents since this question is highly indexed in Google. I think you should be using
self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension
self.tableView.estimatedSectionHeaderHeight = 200 //a rough estimate, doesn't need to be accurate
in your ViewDidLoad. Also, to load a custom UIView to a Header you should really be using viewForHeaderInSection delegate method. You can have a custom Nib file for your header (UIView nib). That Nib must have a controller class which subclasses UITableViewHeaderFooterView like-
class YourCustomHeader: UITableViewHeaderFooterView {
//#IBOutlets, delegation and other methods as per your needs
}
Make sure your Nib file name is the same as the class name just so you don't get confused and it's easier to manage. like YourCustomHeader.xib and YourCustomHeader.swift (containing class YourCustomHeader). Then, just assign YourCustomHeader to your Nib file using identity inspector in the interface builder.
Then register the Nib file as your header view in the main View Controller's viewDidLoad like-
tableView.register(UINib(nibName: "YourCustomHeader", bundle: nil), forHeaderFooterViewReuseIdentifier: "YourCustomHeader")
And then in your heightForHeaderInSection just return UITableViewAutomaticDimension. This is how the delegates should look like-
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "YourCustomHeader") as! YourCustomHeader
return headerView
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return UITableViewAutomaticDimension
}
This is a much simpler and the appropriate way of doing without the "Hackish" ways suggested in the accepted answer since multiple forced layouts could impact your app's performance, especially if you have multiple custom headers in your tableview. Once you do the above method as I suggest, you would notice your Header (and or Footer) view expand and shrink magically based on your custom view's content size (provided you are using AutoLayout in the custom view, i.e. YourCustomHeader, nib file).

Hide separator line on one UITableViewCell

I'm customizing a UITableView. I want to hide the line separating on the last cell ... can i do this?
I know I can do tableView.separatorStyle = UITableViewCellStyle.None but that would affect all the cells of the tableView. I want it to only affect my last cell.
in viewDidLoad, add this line:
self.tableView.separatorColor = [UIColor clearColor];
and in cellForRowAtIndexPath:
for iOS lower versions
if(indexPath.row != self.newCarArray.count-1){
UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(0, 44, 320, 2)];
line.backgroundColor = [UIColor redColor];
[cell addSubview:line];
}
for iOS 7 upper versions (including iOS 8)
if (indexPath.row == self.newCarArray.count-1) {
cell.separatorInset = UIEdgeInsetsMake(0.f, cell.bounds.size.width, 0.f, 0.f);
}
In the UITableViewDataSource cellForRowAtIndexPath method
Swift :
if indexPath.row == {your row number} {
cell.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: .greatestFiniteMagnitude)
}
or :
cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, UIScreen.main.bounds.width)
for default Margin:
cell.separatorInset = UIEdgeInsetsMake(0, tCell.layoutMargins.left, 0, 0)
to show separator end-to-end
cell.separatorInset = .zero
Objective-C:
if (indexPath.row == {your row number}) {
cell.separatorInset = UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, CGFLOAT_MAX);
}
To follow up on Hiren's answer.
in ViewDidLoad and the following line :
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
Or, if you are using XIB's or Storyboards change "separator" to "none" :
And in CellForRowAtIndexPath add this :
CGFloat separatorInset; // Separator x position
CGFloat separatorHeight;
CGFloat separatorWidth;
CGFloat separatorY;
UIImageView *separator;
UIColor *separatorBGColor;
separatorY = cell.frame.size.height;
separatorHeight = (1.0 / [UIScreen mainScreen].scale); // This assures you to have a 1px line height whatever the screen resolution
separatorWidth = cell.frame.size.width;
separatorInset = 15.0f;
separatorBGColor = [UIColor colorWithRed: 204.0/255.0 green: 204.0/255.0 blue: 204.0/255.0 alpha:1.0];
separator = [[UIImageView alloc] initWithFrame:CGRectMake(separatorInset, separatorY, separatorWidth,separatorHeight)];
separator.backgroundColor = separatorBGColor;
[cell addSubView: separator];
Here is an example of the result where I display a tableview with dynamic Cells (but only have a single one with contents). The result being that only that one has a separator and not all the "dummy" ones tableview automatically adds to fill the screen.
EDIT: For those who don't always read the comments, there actually is a better way to do it with a few lines of code :
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
}
If you don't want to draw the separator yourself, use this:
// Hide the cell separator by moving it to the far right
cell.separatorInset = UIEdgeInsetsMake(0, 10000, 0, 0);
This API is only available starting from iOS 7 though.
Set separatorInset.right = .greatestFiniteMagnitude on your cell.
my develop environment is
Xcode 7.0
7A220 Swift 2.0
iOS 9.0
above answers not fully work for me
after try, my finally working solution is:
let indent_large_enought_to_hidden:CGFloat = 10000
cell.separatorInset = UIEdgeInsetsMake(0, indent_large_enought_to_hidden, 0, 0) // indent large engough for separator(including cell' content) to hidden separator
cell.indentationWidth = indent_large_enought_to_hidden * -1 // adjust the cell's content to show normally
cell.indentationLevel = 1 // must add this, otherwise default is 0, now actual indentation = indentationWidth * indentationLevel = 10000 * 1 = -10000
and the effect is:
In Swift 3, Swift 4 and Swift 5, you can write an extension to UITableViewCell like this:
extension UITableViewCell {
func separator(hide: Bool) {
separatorInset.left = hide ? bounds.size.width : 0
}
}
Then you can use this as below (when cell is your cell instance):
cell.separator(hide: false) // Shows separator
cell.separator(hide: true) // Hides separator
It is really better assigning the width of table view cell as left inset instead of assigning it some random number. Because in some screen dimensions, maybe not now but in future your separators can still be visible because that random number may not be enough. Also, in iPad in landscape mode you can't guarantee that your separators will always be invisible.
In your UITableViewCell subclass, override layoutSubviews and hide the _UITableViewCellSeparatorView. Works under iOS 10.
override func layoutSubviews() {
super.layoutSubviews()
subviews.forEach { (view) in
if view.dynamicType.description() == "_UITableViewCellSeparatorView" {
view.hidden = true
}
}
}
Better solution for iOS 7 & 8
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
DLog(#"");
if (cell && indexPath.row == 0 && indexPath.section == 0) {
DLog(#"cell.bounds.size.width %f", cell.bounds.size.width);
cell.separatorInset = UIEdgeInsetsMake(0.f, cell.bounds.size.width, 0.f, 0.0f);
}
}
If your app is rotatable — use 3000.0f for left inset constant or calc it on the fly.
If you try to set right inset you have visible part of separator on the left side of cell on iOS 8.
In iOS 7, the UITableView grouped style cell separator looks a bit different. It looks a bit like this:
I tried Kemenaran's answer of doing this:
cell.separatorInset = UIEdgeInsetsMake(0, 10000, 0, 0);
However that doesn't seem to work for me. I'm not sure why. So I decided to use Hiren's answer, but using UIView instead of UIImageView, and draws the line in the iOS 7 style:
UIColor iOS7LineColor = [UIColor colorWithRed:0.82f green:0.82f blue:0.82f alpha:1.0f];
//First cell in a section
if (indexPath.row == 0) {
UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 1)];
line.backgroundColor = iOS7LineColor;
[cell addSubview:line];
[cell bringSubviewToFront:line];
} else if (indexPath.row == [self.tableViewCellSubtitles count] - 1) {
UIView *line = [[UIView alloc] initWithFrame:CGRectMake(21, 0, self.view.frame.size.width, 1)];
line.backgroundColor = iOS7LineColor;
[cell addSubview:line];
[cell bringSubviewToFront:line];
UIView *lineBottom = [[UIView alloc] initWithFrame:CGRectMake(0, 43, self.view.frame.size.width, 1)];
lineBottom.backgroundColor = iOS7LineColor;
[cell addSubview:lineBottom];
[cell bringSubviewToFront:lineBottom];
} else {
//Last cell in the table view
UIView *line = [[UIView alloc] initWithFrame:CGRectMake(21, 0, self.view.frame.size.width, 1)];
line.backgroundColor = iOS7LineColor;
[cell addSubview:line];
[cell bringSubviewToFront:line];
}
If you use this, make sure you plug in the correct table view height in the second if statement. I hope this is useful for someone.
In Swift using iOS 8.4:
/*
Tells the delegate that the table view is about to draw a cell for a particular row. (optional)
*/
override func tableView(tableView: UITableView,
willDisplayCell cell: UITableViewCell,
forRowAtIndexPath indexPath: NSIndexPath)
{
if indexPath.row == 3 {
// Hiding separator line for only one specific UITableViewCell
cell.separatorInset = UIEdgeInsetsMake(0, cell.bounds.size.width, 0, 0)
}
}
Note: this snippet above will work on UITableView using dynamic cells. The only problem that you can encounter is when you use static cells with categories, a separator type different than none and a grouped style for the table view. In fact, in this particular case it will not hide the last cell of each category. For overcoming that, the solution that I found was to set the cell separator (through IB) to none and then creating and adding manually (through code) your line view to each cell. For an example, please check the snippet below:
/*
Tells the delegate that the table view is about to draw a cell for a particular row. (optional)
*/
override func tableView(tableView: UITableView,
willDisplayCell cell: UITableViewCell,
forRowAtIndexPath indexPath: NSIndexPath)
{
// Row 2 at Section 2
if indexPath.row == 1 && indexPath.section == 1 {
// Hiding separator line for one specific UITableViewCell
cell.separatorInset = UIEdgeInsetsMake(0, cell.bounds.size.width, 0, 0)
// Here we add a line at the bottom of the cell (e.g. here at the second row of the second section).
let additionalSeparatorThickness = CGFloat(1)
let additionalSeparator = UIView(frame: CGRectMake(0,
cell.frame.size.height - additionalSeparatorThickness,
cell.frame.size.width,
additionalSeparatorThickness))
additionalSeparator.backgroundColor = UIColor.redColor()
cell.addSubview(additionalSeparator)
}
}
I do not believe this approach will work under any circumstance with dynamic cells...
if (indexPath.row == self.newCarArray.count-1) {
cell.separatorInset = UIEdgeInsetsMake(0.f, cell.bounds.size.width, 0.f, 0.f);
}
It doesn't matter which tableview method you do it in for dynamic cells the cell you changed the inset property on will always have the inset property set now every time it is dequeued causing a rampage of missing line separators... That is until you change it yourself.
Something like this worked for me:
if indexPath.row == franchises.count - 1 {
cell.separatorInset = UIEdgeInsetsMake(0, cell.contentView.bounds.width, 0, 0)
} else {
cell.separatorInset = UIEdgeInsetsMake(0, 0, cell.contentView.bounds.width, 0)
}
That way you update ur data structure state at every load
In willdisplaycell:
cell.separatorInset = UIEdgeInsetsMake(0, cell.bounds.size.width, 0, 0)
The much more simple and logical is to do this:
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
return [[UIView alloc] initWithFrame:CGRectZero];
}
In most cases you don't want to see only the last table view cell separator. And this approach removes only the last table view cell separator, and you don't need to think about Auto Layout issues (i.e. rotating device) or hardcode values to set up separator insets.
Use this subclass, set separatorInset does not work for iOS 9.2.1, content would be squeezed.
#interface NSPZeroMarginCell : UITableViewCell
#property (nonatomic, assign) BOOL separatorHidden;
#end
#implementation NSPZeroMarginCell
- (void) layoutSubviews {
[super layoutSubviews];
for (UIView *view in self.subviews) {
if (![view isKindOfClass:[UIControl class]]) {
if (CGRectGetHeight(view.frame) < 3) {
view.hidden = self.separatorHidden;
}
}
}
}
#end
https://gist.github.com/liruqi/9a5add4669e8d9cd3ee9
Using Swift 3 and adopting the fastest hacking-method, you can improve code using extensions:
extension UITableViewCell {
var isSeparatorHidden: Bool {
get {
return self.separatorInset.right != 0
}
set {
if newValue {
self.separatorInset = UIEdgeInsetsMake(0, self.bounds.size.width, 0, 0)
} else {
self.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0)
}
}
}
}
Then, when you configure cell:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifier", for: indexPath)
switch indexPath.row {
case 3:
cell.isSeparatorHidden = true
default:
cell.isSeparatorHidden = false
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath)
if cell.isSeparatorHidden {
// do stuff
}
}
if([_data count] == 0 ){
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];// [self tableView].=YES;
} else {
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];//// [self tableView].hidden=NO;
}
The best way to achieve this is to turn off default line separators, subclass UITableViewCell and add a custom line separator as a subview of the contentView - see below a custom cell that is used to present an object of type SNStock that has two string properties, ticker and name:
import UIKit
private let kSNStockCellCellHeight: CGFloat = 65.0
private let kSNStockCellCellLineSeparatorHorizontalPaddingRatio: CGFloat = 0.03
private let kSNStockCellCellLineSeparatorBackgroundColorAlpha: CGFloat = 0.3
private let kSNStockCellCellLineSeparatorHeight: CGFloat = 1
class SNStockCell: UITableViewCell {
private let primaryTextColor: UIColor
private let secondaryTextColor: UIColor
private let customLineSeparatorView: UIView
var showsCustomLineSeparator: Bool {
get {
return !customLineSeparatorView.hidden
}
set(showsCustomLineSeparator) {
customLineSeparatorView.hidden = !showsCustomLineSeparator
}
}
var customLineSeparatorColor: UIColor? {
get {
return customLineSeparatorView.backgroundColor
}
set(customLineSeparatorColor) {
customLineSeparatorView.backgroundColor = customLineSeparatorColor?.colorWithAlphaComponent(kSNStockCellCellLineSeparatorBackgroundColorAlpha)
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(reuseIdentifier: String, primaryTextColor: UIColor, secondaryTextColor: UIColor) {
self.primaryTextColor = primaryTextColor
self.secondaryTextColor = secondaryTextColor
self.customLineSeparatorView = UIView(frame:CGRectZero)
super.init(style: UITableViewCellStyle.Subtitle, reuseIdentifier:reuseIdentifier)
selectionStyle = UITableViewCellSelectionStyle.None
backgroundColor = UIColor.clearColor()
contentView.addSubview(customLineSeparatorView)
customLineSeparatorView.hidden = true
}
override func prepareForReuse() {
super.prepareForReuse()
self.showsCustomLineSeparator = false
}
// MARK: Layout
override func layoutSubviews() {
super.layoutSubviews()
layoutCustomLineSeparator()
}
private func layoutCustomLineSeparator() {
let horizontalPadding: CGFloat = bounds.width * kSNStockCellCellLineSeparatorHorizontalPaddingRatio
let lineSeparatorWidth: CGFloat = bounds.width - horizontalPadding * 2;
customLineSeparatorView.frame = CGRectMake(horizontalPadding,
kSNStockCellCellHeight - kSNStockCellCellLineSeparatorHeight,
lineSeparatorWidth,
kSNStockCellCellLineSeparatorHeight)
}
// MARK: Public Class API
class func cellHeight() -> CGFloat {
return kSNStockCellCellHeight
}
// MARK: Public API
func configureWithStock(stock: SNStock) {
textLabel!.text = stock.ticker as String
textLabel!.textColor = primaryTextColor
detailTextLabel!.text = stock.name as String
detailTextLabel!.textColor = secondaryTextColor
setNeedsLayout()
}
}
To disable the default line separator use, tableView.separatorStyle = UITableViewCellSeparatorStyle.None;. The consumer side is relatively simple, see example below:
private func stockCell(tableView: UITableView, indexPath:NSIndexPath) -> UITableViewCell {
var cell : SNStockCell? = tableView.dequeueReusableCellWithIdentifier(stockCellReuseIdentifier) as? SNStockCell
if (cell == nil) {
cell = SNStockCell(reuseIdentifier:stockCellReuseIdentifier, primaryTextColor:primaryTextColor, secondaryTextColor:secondaryTextColor)
}
cell!.configureWithStock(stockAtIndexPath(indexPath))
cell!.showsCustomLineSeparator = true
cell!.customLineSeparatorColor = tintColor
return cell!
}
For Swift 2:
add the following line to viewDidLoad():
tableView.separatorColor = UIColor.clearColor()
cell.separatorInset = UIEdgeInsetsMake(0.0, cell.bounds.size.width, 0.0, -cell.bounds.size.width)
works well in iOS 10.2
Swift 5 - iOS13+
When you are defininig your table, just add:
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
// Removes separator lines
tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
return UIView()
}
The magic line is tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
Try the below code, might help you resolve your problem
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString* reuseIdentifier = #"Contact Cell";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
if (nil == cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
if (indexPath.row != 10) {//Specify the cell number
cell.backgroundView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bgWithLine.png"]];
} else {
cell.backgroundView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bgWithOutLine.png"]];
}
}
return cell;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *cellId = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
NSInteger lastRowIndexInSection = [tableView numberOfRowsInSection:indexPath.section] - 1;
if (row == lastRowIndexInSection) {
CGFloat halfWidthOfCell = cell.frame.size.width / 2;
cell.separatorInset = UIEdgeInsetsMake(0, halfWidthOfCell, 0, halfWidthOfCell);
}
}
You have to take custom cell and add Label and set constraint such as label should cover entire cell area.
and write the below line in constructor.
- (void)awakeFromNib {
// Initialization code
self.separatorInset = UIEdgeInsetsMake(0, 10000, 0, 0);
//self.layoutMargins = UIEdgeInsetsZero;
[self setBackgroundColor:[UIColor clearColor]];
[self setSelectionStyle:UITableViewCellSelectionStyleNone];
}
Also set UITableView Layout margin as follow
tblSignup.layoutMargins = UIEdgeInsetsZero;
I couldn't hide the separator on a specific cell except using the following workaround
- (void)layoutSubviews {
[super layoutSubviews];
[self hideCellSeparator];
}
// workaround
- (void)hideCellSeparator {
for (UIView *view in self.subviews) {
if (![view isKindOfClass:[UIControl class]]) {
[view removeFromSuperview];
}
}
}
For iOS7 and above, the cleaner way is to use INFINITY instead of hardcoded value. You don't have to worry on updating the cell when the screen rotates.
if (indexPath.row == <row number>) {
cell.separatorInset = UIEdgeInsetsMake(0, INFINITY, 0, 0);
}
As (many) others have pointed out, you can easily hide all UITableViewCell separators by simply turning them off for the entire UITableView itself; eg in your UITableViewController
- (void)viewDidLoad {
...
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
...
}
Unfortunately, its a real PITA to do on a per-cell basis, which is what you are really asking.
Personally, I've tried numerous permutations of changing the cell.separatorInset.left, again, as (many) others have suggested, but the problem is, to quote Apple (emphasis added):
"...You can use this property to add space between the current cell’s contents and the left and right edges of the table. Positive inset values move the cell content and cell separator inward and away from the table edges..."
So if you try to 'hide' the separator by shoving it offscreen to the right, you can end up also indenting your cell's contentView too. As suggested by crifan, you can then try to compensate for this nasty side-effect by setting cell.indentationWidth and cell.indentationLevel appropriately to move everything back, but I've found this to also be unreliable (content still getting indented...).
The most reliable way I've found is to over-ride layoutSubviews in a simple UITableViewCell subclass and set the right inset so that it hits the left inset, making the separator have 0 width and so invisible [this needs to be done in layoutSubviews to automatically handle rotations]. I also add a convenience method to my subclass to turn this on.
#interface MyTableViewCellSubclass()
#property BOOL separatorIsHidden;
#end
#implementation MyTableViewCellSubclass
- (void)hideSeparator
{
_separatorIsHidden = YES;
}
- (void)layoutSubviews
{
[super layoutSubviews];
if (_separatorIsHidden) {
UIEdgeInsets inset = self.separatorInset;
inset.right = self.bounds.size.width - inset.left;
self.separatorInset = inset;
}
}
#end
Caveat: there isn't a reliable way to restore the original right inset, so you cant 'un-hide' the separator, hence why I'm using an irreversible hideSeparator method (vs exposing separatorIsHidden). Please note the separatorInset persists across reused cells so, because you can't 'un-hide', you need to keep these hidden-separator cells isolated in their own reuseIdentifier.
if the accepted answer doesn't work, you can try this:
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
return 0.01f; }
It's great ;)
My requirement was to hide the separator between 4th and 5th cell. I achieved it by
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.row == 3)
{
cell.separatorInset = UIEdgeInsetsMake(0, cell.bounds.size.width, 0, 0);
}
}
Inside the tableview cell class. put these line of code
separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: self.bounds.size.width)

Resources