How to set textAlignment for UITableViewHeaderFooterView? - ios

I make a UITableViewControl. I need to set textAlignment for UITableViewHeaderFooterView as shown below. But it's not working.
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
[header.textLabel setTextColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"button.png"]]];
header.textLabel.textAlignment = NSTextAlignmentCenter;

Create a view,on this view add a label,and set the view as the header view on your table:
self.tableView.headerView = view

If you want to have a header filled by a stretched image, try to use contentView instead of textLabel
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return HEADER_HEIGHT;
}
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
UIImage *originImage = [UIImage imageNamed:#"yourImage"];
CGSize size = header.frame.size;
UIGraphicsBeginImageContext(size);
[originImage drawInRect:CGRectMake(0,0,size.width,size.height)];
UIImage* resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
header.contentView.backgroundColor = [UIColor colorWithPatternImage:resizedImage];
}

As suggested by #wg_hij, we can use custom UIView as header view for table view.
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let sectionInfo = fetchedResultsController!.sections! as [NSFetchedResultsSectionInfo]
let headerTitle = sectionInfo[section].name
let headerHeight:CGFloat = tableView.sectionHeaderHeight
let headerView = HeaderView(frame: CGRectMake(0, 0, tableView.width, headerHeight), withHeaderLable: headerTitle)
return headerView
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 40;//custom height
}
HeaderView will be something like:
class HeaderView: UIView {
var headerLbl: UILabel?
init(frame: CGRect, withHeaderLable headerText: String) {
super.init(frame: frame)
backgroundColor = UIColor.clearColor()
makeUpHeaderLabel(headerText)
}
func makeUpHeaderLabel(lblText: String) {
if headerLbl == nil {
headerLbl = UILabel(frame: CGRectMake(0, 0, 10, 10))
headerLbl!.makeRoundedRect()
headerLbl!.bgColorName = ColorPaletteCP1
headerLbl!.fontName = BHTypoMI14
headerLbl!.textAlignment = .Center
headerLbl!.baselineAdjustment = .AlignCenters
addSubview(headerLbl!)
}
headerLbl!.text = lblText
headerLbl!.sizeToFit()
let frame = headerLbl!.frame
headerLbl!.frame = CGRectMake(0, 0, frame.size.width + 32, frame.height + 8)
headerLbl!.center = CGPointMake(width / 2, height / 2)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Using this custom header view, we can do anything related to look-n-feel!

Related

iOS 11 navigation bar height customizing

Now in iOS 11, the sizeThatFits method is not called from UINavigationBar subclasses. Changing the frame of UINavigationBar causes glitches and wrong insets.
So, any ideas how to customize navbar height now?
According to Apple developers (look here, here and here), changing navigation bar height in iOS 11 is not supported. Here they suggest to do workarounds like having a view under the navigation bar (but outside of it) and then remove the nav bar border. As a result, you will have this in storyboard:
look like this on the device:
Now you can do a workaround that was suggested in the other answers: create a custom subclass of UINavigationBar, add your custom large subview to it, override sizeThatFits and layoutSubviews, then set additionalSafeAreaInsets.top for the navigation's top controller to the difference customHeight - 44px, but the bar view will still be the default 44px, even though visually everything will look perfect. I didn't try overriding setFrame, maybe it works, however, as Apple developer wrote in one of the links above: "...and neither is [supported] changing the frame of a navigation bar that is owned by a UINavigationController (the navigation controller will happily stomp on your frame changes whenever it deems fit to do so)."
In my case the above workaround made views to look like this (debug view to show borders):
As you can see, the visual appearance is quite good, the additionalSafeAreaInsets correctly pushed the content down, the big navigation bar is visible, however I have a custom button in this bar and only the area that goes under the standard 44 pixel nav bar is clickable (green area in the image). Touches below the standard navigation bar height doesn't reach my custom subview, so I need the navigation bar itself to be resized, which the Apple developers say is not supported.
Updated 07 Jan 2018
This code is support XCode 9.2, iOS 11.2
I had the same problem. Below is my solution. I assume that height size is 66.
Please choose my answer if it helps you.
Create CINavgationBar.swift
import UIKit
#IBDesignable
class CINavigationBar: UINavigationBar {
//set NavigationBar's height
#IBInspectable var customHeight : CGFloat = 66
override func sizeThatFits(_ size: CGSize) -> CGSize {
return CGSize(width: UIScreen.main.bounds.width, height: customHeight)
}
override func layoutSubviews() {
super.layoutSubviews()
print("It called")
self.tintColor = .black
self.backgroundColor = .red
for subview in self.subviews {
var stringFromClass = NSStringFromClass(subview.classForCoder)
if stringFromClass.contains("UIBarBackground") {
subview.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: customHeight)
subview.backgroundColor = .green
subview.sizeToFit()
}
stringFromClass = NSStringFromClass(subview.classForCoder)
//Can't set height of the UINavigationBarContentView
if stringFromClass.contains("UINavigationBarContentView") {
//Set Center Y
let centerY = (customHeight - subview.frame.height) / 2.0
subview.frame = CGRect(x: 0, y: centerY, width: self.frame.width, height: subview.frame.height)
subview.backgroundColor = .yellow
subview.sizeToFit()
}
}
}
}
Set Storyboard
Set Custom NavigationBar class
Add TestView + Set SafeArea
ViewController.swift
import UIKit
class ViewController: UIViewController {
var navbar : UINavigationBar!
#IBOutlet weak var testView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
//update NavigationBar's frame
self.navigationController?.navigationBar.sizeToFit()
print("NavigationBar Frame : \(String(describing: self.navigationController!.navigationBar.frame))")
}
//Hide Statusbar
override var prefersStatusBarHidden: Bool {
return true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(false)
//Important!
if #available(iOS 11.0, *) {
//Default NavigationBar Height is 44. Custom NavigationBar Height is 66. So We should set additionalSafeAreaInsets to 66-44 = 22
self.additionalSafeAreaInsets.top = 22
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
SecondViewController.swift
import UIKit
class SecondViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Create BackButton
var backButton: UIBarButtonItem!
let backImage = imageFromText("Back", font: UIFont.systemFont(ofSize: 16), maxWidth: 1000, color:UIColor.white)
backButton = UIBarButtonItem(image: backImage, style: UIBarButtonItemStyle.plain, target: self, action: #selector(SecondViewController.back(_:)))
self.navigationItem.leftBarButtonItem = backButton
self.navigationItem.leftBarButtonItem?.setBackgroundVerticalPositionAdjustment(-10, for: UIBarMetrics.default)
}
override var prefersStatusBarHidden: Bool {
return true
}
#objc func back(_ sender: UITabBarItem){
self.navigationController?.popViewController(animated: true)
}
//Helper Function : Get String CGSize
func sizeOfAttributeString(_ str: NSAttributedString, maxWidth: CGFloat) -> CGSize {
let size = str.boundingRect(with: CGSize(width: maxWidth, height: 1000), options:(NSStringDrawingOptions.usesLineFragmentOrigin), context:nil).size
return size
}
//Helper Function : Convert String to UIImage
func imageFromText(_ text:NSString, font:UIFont, maxWidth:CGFloat, color:UIColor) -> UIImage
{
let paragraph = NSMutableParagraphStyle()
paragraph.lineBreakMode = NSLineBreakMode.byWordWrapping
paragraph.alignment = .center // potentially this can be an input param too, but i guess in most use cases we want center align
let attributedString = NSAttributedString(string: text as String, attributes: [NSAttributedStringKey.font: font, NSAttributedStringKey.foregroundColor: color, NSAttributedStringKey.paragraphStyle:paragraph])
let size = sizeOfAttributeString(attributedString, maxWidth: maxWidth)
UIGraphicsBeginImageContextWithOptions(size, false , 0.0)
attributedString.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Yellow is barbackgroundView. Black opacity is BarContentView.
And I removed BarContentView's backgroundColor.
That's It.
this works for me :
- (CGSize)sizeThatFits:(CGSize)size {
CGSize sizeThatFit = [super sizeThatFits:size];
if ([UIApplication sharedApplication].isStatusBarHidden) {
if (sizeThatFit.height < 64.f) {
sizeThatFit.height = 64.f;
}
}
return sizeThatFit;
}
- (void)setFrame:(CGRect)frame {
if ([UIApplication sharedApplication].isStatusBarHidden) {
frame.size.height = 64;
}
[super setFrame:frame];
}
- (void)layoutSubviews
{
[super layoutSubviews];
for (UIView *subview in self.subviews) {
if ([NSStringFromClass([subview class]) containsString:#"BarBackground"]) {
CGRect subViewFrame = subview.frame;
subViewFrame.origin.y = 0;
subViewFrame.size.height = 64;
[subview setFrame: subViewFrame];
}
if ([NSStringFromClass([subview class]) containsString:#"BarContentView"]) {
CGRect subViewFrame = subview.frame;
subViewFrame.origin.y = 20;
subViewFrame.size.height = 44;
[subview setFrame: subViewFrame];
}
}
}
Added:
The problem is solved in iOS 11 beta 6 ,so the code below is of no use ^_^
Original answer:
Solved with code below :
(I always want the navigationBar.height + statusBar.height == 64 whether the hidden of statusBar is true or not)
#implementation P1AlwaysBigNavigationBar
- (CGSize)sizeThatFits:(CGSize)size {
CGSize sizeThatFit = [super sizeThatFits:size];
if ([UIApplication sharedApplication].isStatusBarHidden) {
if (sizeThatFit.height < 64.f) {
sizeThatFit.height = 64.f;
}
}
return sizeThatFit;
}
- (void)setFrame:(CGRect)frame {
if ([UIApplication sharedApplication].isStatusBarHidden) {
frame.size.height = 64;
}
[super setFrame:frame];
}
- (void)layoutSubviews
{
[super layoutSubviews];
if (![UIApplication sharedApplication].isStatusBarHidden) {
return;
}
for (UIView *subview in self.subviews) {
NSString* subViewClassName = NSStringFromClass([subview class]);
if ([subViewClassName containsString:#"UIBarBackground"]) {
subview.frame = self.bounds;
}else if ([subViewClassName containsString:#"UINavigationBarContentView"]) {
if (subview.height < 64) {
subview.y = 64 - subview.height;
}else {
subview.y = 0;
}
}
}
}
#end
Simplified with Swift 4.
class CustomNavigationBar : UINavigationBar {
private let hiddenStatusBar: Bool
// MARK: Init
init(hiddenStatusBar: Bool = false) {
self.hiddenStatusBar = hiddenStatusBar
super.init(frame: .zero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Overrides
override func layoutSubviews() {
super.layoutSubviews()
if #available(iOS 11.0, *) {
for subview in self.subviews {
let stringFromClass = NSStringFromClass(subview.classForCoder)
if stringFromClass.contains("BarBackground") {
subview.frame = self.bounds
} else if stringFromClass.contains("BarContentView") {
let statusBarHeight = self.hiddenStatusBar ? 0 : UIApplication.shared.statusBarFrame.height
subview.frame.origin.y = statusBarHeight
subview.frame.size.height = self.bounds.height - statusBarHeight
}
}
}
}
}
Along with overriding -layoutSubviews and -setFrame: you should check out the newly added UIViewController's additionalSafereaInsets property (Apple Documentation) if you do not want the resized navigation bar hiding your content.
Although it's fixed in beta 4, it seems the background image of the nav bar does not scale with the actual view (you can verify this by looking at at in the view-hierarchy viewer). A workaround for now is to override layoutSubviews in your custom UINavigationBar and then use this code:
- (void)layoutSubviews
{
[super layoutSubviews];
for (UIView *subview in self.subviews) {
if ([NSStringFromClass([subview class]) containsString:#"BarBackground"]) {
CGRect subViewFrame = subview.frame;
subViewFrame.origin.y = -20;
subViewFrame.size.height = CUSTOM_FIXED_HEIGHT+20;
[subview setFrame: subViewFrame];
}
}
}
If you notice, the bar background in fact has an offset of -20 to make it appear behind the status bar, so the calculation above adds that in.
on Xcode 9 Beta 6 I still have the issue. The Bar always looks 44 pixel height and it is pushed under the status bar.
In order to solve that I made a subclass with #strangetimes code (in Swift)
class NavigationBar: UINavigationBar {
override func layoutSubviews() {
super.layoutSubviews()
for subview in self.subviews {
var stringFromClass = NSStringFromClass(subview.classForCoder)
print("--------- \(stringFromClass)")
if stringFromClass.contains("BarBackground") {
subview.frame.origin.y = -20
subview.frame.size.height = 64
}
}
}
}
and I place the bar lower than the status bar
let newNavigationBar = NavigationBar(frame: CGRect(origin: CGPoint(x: 0,
y: 20),
size: CGSize(width: view.frame.width,
height: 64)
)
)
This works well for the regular navigation bar. If your using the LargeTitle this wont work well because the titleView size isn't going to be a fixed height of 44 points. But for the regular view this should be suffice.
Like #frangulyan apple suggested to add a view beneath the navBar and hide the thin line (shadow image). This is what I came up with below. I added an uiview to the navigationItem's titleView and then added an imageView inside that uiview. I removed the thin line (shadow image). The uiview I added is the same exact color as the navBar. I added a uiLabel inside that view and that's it.
Here's the 3d image. The extended view is behind the usernameLabel underneath the navBar. Its gray and has a thin line underneath of it. Just anchor your collectionView or whatever underneath of the thin separatorLine.
The 9 steps are explained above each line of code:
class ExtendedNavController: UIViewController {
fileprivate let extendedView: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .white
return view
}()
fileprivate let separatorLine: UIView = {
let view = UIView()
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .gray
return view
}()
fileprivate let usernameLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.systemFont(ofSize: 14)
label.text = "username goes here"
label.textAlignment = .center
label.lineBreakMode = .byTruncatingTail
label.numberOfLines = 1
return label
}()
fileprivate let myTitleView: UIView = {
let view = UIView()
view.backgroundColor = .white
return view
}()
fileprivate let profileImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.clipsToBounds = true
imageView.backgroundColor = .darkGray
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
// 1. the navBar's titleView has a height of 44, set myTitleView height and width both to 44
myTitleView.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
// 2. set myTitleView to the nav bar's titleView
navigationItem.titleView = myTitleView
// 3. get rid of the thin line (shadow Image) underneath the navigationBar
navigationController?.navigationBar.setValue(true, forKey: "hidesShadow")
navigationController?.navigationBar.layoutIfNeeded()
// 4. set the navigationBar's tint color to the color you want
navigationController?.navigationBar.barTintColor = UIColor(red: 249.0/255.0, green: 249.0/255.0, blue: 249.0/255.0, alpha: 1.0)
// 5. set extendedView's background color to the same exact color as the navBar's background color
extendedView.backgroundColor = UIColor(red: 249.0/255.0, green: 249.0/255.0, blue: 249.0/255.0, alpha: 1.0)
// 6. set your imageView to get pinned inside the titleView
setProfileImageViewAnchorsInsideMyTitleView()
// 7. set the extendedView's anchors directly underneath the navigation bar
setExtendedViewAndSeparatorLineAnchors()
// 8. set the usernameLabel's anchors inside the extendedView
setNameLabelAnchorsInsideTheExtendedView()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
// 9. **Optional** If you want the shadow image to show on other view controllers when popping or pushing
navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
navigationController?.navigationBar.setValue(false, forKey: "hidesShadow")
navigationController?.navigationBar.layoutIfNeeded()
}
func setExtendedViewAndSeparatorLineAnchors() {
view.addSubview(extendedView)
view.addSubview(separatorLine)
extendedView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
extendedView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
extendedView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
extendedView.heightAnchor.constraint(equalToConstant: 29.5).isActive = true
separatorLine.topAnchor.constraint(equalTo: extendedView.bottomAnchor).isActive = true
separatorLine.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
separatorLine.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
separatorLine.heightAnchor.constraint(equalToConstant: 0.5).isActive = true
}
func setProfileImageViewAnchorsInsideMyTitleView() {
myTitleView.addSubview(profileImageView)
profileImageView.topAnchor.constraint(equalTo: myTitleView.topAnchor).isActive = true
profileImageView.centerXAnchor.constraint(equalTo: myTitleView.centerXAnchor).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 44).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: 44).isActive = true
// round the profileImageView
profileImageView.layoutIfNeeded()
profileImageView.layer.cornerRadius = profileImageView.frame.width / 2
}
func setNameLabelAnchorsInsideTheExtendedView() {
extendedView.addSubview(usernameLabel)
usernameLabel.topAnchor.constraint(equalTo: extendedView.topAnchor).isActive = true
usernameLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
usernameLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
}
}
This is what I use. It works for regular content (44.0 px) if you use UISearchBar as title or other views that modify the size of the bar content, you must update the values accordingly. Use this at your own risk since it might brake at some point.
This is the navbar with 90.0px height hardcoded, working on both iOS 11 and older versions. You might have to add some insets to the UIBarButtonItem for pre iOS 11 to look the same.
class NavBar: UINavigationBar {
override init(frame: CGRect) {
super.init(frame: frame)
if #available(iOS 11, *) {
translatesAutoresizingMaskIntoConstraints = false
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
return CGSize(width: UIScreen.main.bounds.width, height: 70.0)
}
override func layoutSubviews() {
super.layoutSubviews()
guard #available(iOS 11, *) else {
return
}
frame = CGRect(x: frame.origin.x, y: 0, width: frame.size.width, height: 90)
if let parent = superview {
parent.layoutIfNeeded()
for view in parent.subviews {
let stringFromClass = NSStringFromClass(view.classForCoder)
if stringFromClass.contains("NavigationTransition") {
view.frame = CGRect(x: view.frame.origin.x, y: frame.size.height - 64, width: view.frame.size.width, height: parent.bounds.size.height - frame.size.height + 4)
}
}
}
for subview in self.subviews {
var stringFromClass = NSStringFromClass(subview.classForCoder)
if stringFromClass.contains("BarBackground") {
subview.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: 90)
subview.backgroundColor = .yellow
}
stringFromClass = NSStringFromClass(subview.classForCoder)
if stringFromClass.contains("BarContent") {
subview.frame = CGRect(x: subview.frame.origin.x, y: 40, width: subview.frame.width, height: subview.frame.height)
}
}
}
}
And you add it to a UINavigationController subclass like this:
class CustomBarNavigationViewController: UINavigationController {
init() {
super.init(navigationBarClass: NavBar.self, toolbarClass: nil)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override init(rootViewController: UIViewController) {
super.init(navigationBarClass: NavBar.self, toolbarClass: nil)
self.viewControllers = [rootViewController]
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
I was doubling the height of my navigation bar so I could add a row of status icons above the default navigation controls, by subclassing UINavigationBar and using sizeThatFits to override the height. Fortunately this has the same effect, and is simpler, with fewer side effects. I tested it with iOS 8 through 11. Put this in your view controller:
- (void)viewDidLoad {
[super viewDidLoad];
if (self.navigationController) {
self.navigationItem.prompt = #" "; // this adds empty space on top
}
}

How to implement UI like iCarousel Rotary type, Objective-C?

I want to implement this type of UI (Horizontal Scrolling).
I know its kind of "iCarousel", Type = iCarouselTypeRotary. I tried with this library but I am getting this type UI. I cant able to customize fully:
If anyone know how to do this UI in native way orelse any library, please let me know. Any inputs will be appreciated.
The iCarousel library provides the iCarouselTypeCustom type.
The following is a custom example.
override func awakeFromNib() {
super.awakeFromNib()
for i in 0 ... 6 {
items.append(i)
}
}
override func viewDidLoad() {
super.viewDidLoad()
carousel.type = .custom
}
func numberOfItems(in carousel: iCarousel) -> Int {
return items.count
}
func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView {
var label: UILabel
var itemView: UIImageView
if let view = view as? UIImageView {
itemView = view
label = itemView.viewWithTag(1) as! UILabel
} else {
itemView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
itemView.image = UIImage(named: "page.png")
itemView.layer.cornerRadius = 5
itemView.contentMode = .center
label = UILabel(frame: itemView.bounds)
label.backgroundColor = .clear
label.textAlignment = .center
label.font = label.font.withSize(50)
label.tag = 1
itemView.addSubview(label)
}
label.text = "\(items[index])"
return itemView
}
func carousel(_ carousel: iCarousel, valueFor option: iCarouselOption, withDefault value: CGFloat) -> CGFloat {
switch option {
case .visibleItems:
let elemento:Int = self.carousel.currentItemIndex as Int
print(elemento)
if elemento == 0 {
return 2;
}else if elemento == items.count-1 {
return 2;
}else {
return 3;
}
default:
return value
}
}
func carousel(_ carousel: iCarousel, itemTransformForOffset offset: CGFloat, baseTransform transform: CATransform3D) -> CATransform3D {
let offsetFactor:CGFloat = self.carousel(carousel, valueFor: .spacing, withDefault: 1.25) * carousel.itemWidth
let zFactor: CGFloat = 400.0
let normalFactor: CGFloat = 0
let shrinkFactor: CGFloat = 100.0
let f: CGFloat = sqrt(offset * offset + 1)-1
var trans = transform
trans = CATransform3DTranslate(trans, offset * offsetFactor, f * normalFactor, f * (-zFactor))
trans = CATransform3DScale(trans, 1 / (f / shrinkFactor + 1.0), 1 / (f / shrinkFactor + 1.0), 1.0 )
return trans
}
func carousel(_ carousel: iCarousel, shouldSelectItemAt index: Int) -> Bool {
return true
}
Finally I did with custom view and I have achieved UI as I need it. Here, I am providing my code for someone needy.
- (void)viewDidLoad
{
[super viewDidLoad];
_iCarouselItems = [[NSMutableArray alloc]init];
for (int i = 0; i < 10; i++)
{
[_iCarouselItems addObject:#(i)];
}
self.iCarouselView.dataSource = self;
self.iCarouselView.delegate = self;
_iCarouselView.type = iCarouselTypeCustom;
dispatch_async(dispatch_get_main_queue(), ^{
[_iCarouselView reloadData];
});
}
#pragma mark iCarousel methods
- (NSInteger)numberOfItemsInCarousel:(iCarousel *)carousel
{
return [_iCarouselItems count];
}
- (UIView *)carousel:(iCarousel *)carousel viewForItemAtIndex:(NSInteger)index reusingView:(UIView *)view
{
UILabel *label = nil;
//create new view if no view is available for recycling
if (view == nil)
{
NSLog(#"viewForItemAtIndex is %ld",(long)index);
//don’t do anything specific to the index within
//this `if (view == nil) {…}` statement because the view will be
//recycled and used with other index values later
view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200.0f)];
// ((UIImageView *)view).image = [UIImage imageNamed:#"smiley-400x400.jpg"];
view.contentMode = UIViewContentModeCenter;
view.backgroundColor = [UIColor whiteColor];
view.layer.cornerRadius = 8;
view.layer.masksToBounds = true;
view.layer.borderColor = [UIColor grayColor].CGColor;
view.layer.borderWidth = 2;
label = [[UILabel alloc] initWithFrame:view.bounds];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = NSTextAlignmentCenter;
label.font = [label.font fontWithSize:50];
label.tag = 1;
[view addSubview:label];
}
else
{
//get a reference to the label in the recycled view
label = (UILabel *)[view viewWithTag:1];
}
label.text = [_iCarouselItems[index] stringValue];
return view;
}
- (CATransform3D)carousel:(iCarousel *)carousel itemTransformForOffset:(CGFloat)offset baseTransform:(CATransform3D)transform
{
CGFloat offsetFactor = [self carousel:carousel valueForOption:iCarouselOptionSpacing withDefault:0.3]*carousel.itemWidth;
CGFloat zFactor = 400.0;
CGFloat normalFactor = 0;
CGFloat shrinkFactor = 100.0;
CGFloat f = sqrt(offset * offset + 1)-1;
transform = CATransform3DTranslate(transform, offset * offsetFactor, f * normalFactor, f * (-zFactor));
transform = CATransform3DScale(transform, 1 / (f / shrinkFactor + 1.0), 1 / (f / shrinkFactor + 1.0), 1.0 );
return transform;
}
- (BOOL)carousel:(iCarousel *)carousel shouldSelectItemAtIndex:(NSInteger)index
{
return true;
}
- (void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index
{
NSLog(#"Selected carouselindex is %ld",(long)index);
}
- (NSInteger)numberOfPlaceholdersInCarousel:(iCarousel *)carousel
{
//note: placeholder views are only displayed on some carousels if wrapping is disabled
return 0;
}
There are several solutions available for 3D carousels.
Take a look at that one for example:https://www.cocoacontrols.com/controls/parallaxcarousel
You can find the source code on Github. This project uses CABasicAnimation und you can install it using CocaPods.

Hiding Tableview section headers on the fly

I am trying to hide and display section headers when there is or isn't data populating the tableview. The code I have now works as intended occasionally, but mostly, one or both of the section headers will remain displayed, (However, if I drag the header off screen when there is no data it will disappear as intended).
This is the code I am using to hide/unhide the sections.
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//Create custom header titles for desired header spacing
if (section == 0) {
UIView *headerView;
if (self.searchUsers.count || self.searchTracks.count)
{
headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
}
else{
headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
}
HeaderTitleLabel *headerTitle = [[HeaderTitleLabel alloc] initWithFrame:CGRectMake(17, 10, 150, 20) headerText:#"USERS"];
[headerView addSubview:headerTitle];
return headerView;
}
else if (section == 1){
UIView *headerView;
if (self.searchUsers.count || self.searchTracks.count)
{
headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
}
else{
headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
}
HeaderTitleLabel *headerTitle = [[HeaderTitleLabel alloc] initWithFrame:CGRectMake(17, 0, 150, 20) headerText:#"SONGS"];
[headerView addSubview:headerTitle];
return headerView;
}
else
return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
//custom header spacing
if (section == 0) {
if (self.searchUsers.count || self.searchTracks.count)
{
return 40;
}
else
return 0;
}
else if (section == 1) {
if (self.searchUsers.count || self.searchTracks.count)
{
return 50;
}
else
return 0;
}
else
return 0;
}
I check if my array has objects, if not then set the frame's height to 0. This doesn't seem to be working though. Any ideas how I should go about doing this? Thank you.
Your model should drive your table view. Don't just return a 'number of rows' value from your model, but also a 'number of sections' value.
Consider an array that contains two arrays as your model.
You are using wrong approach of table view. Can you clarify what do you exactly want to do. I could help you. Rather then UIView use UITableView Cell.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (self.searchUsers.count || self.searchTracks.count)
{
if (indexPath.section ==0) {
static NSString *simpleTableIdentifier = #"CategoryCell";
CategoryCell *cell = (CategoryCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CategoryCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.lbl_CatName.text = [[self.CategoryArray objectAtIndex:indexPath.row] objectForKey:kNAME];
return cell;}
else if (indexPath.section ==1){
static NSString *EarnPointIdentifier = #"EarnPointTableCell";
EarnPointTableCell *EarnPointcell = (EarnPointTableCell *)[tableView dequeueReusableCellWithIdentifier:EarnPointIdentifier];
if (EarnPointcell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"EarnPointTableCell" owner:self options:nil];
EarnPointcell = [nib objectAtIndex:0];
}
return EarnPointcell ;
}
else{
//it will have transparent background and every thing will be transparent
static NSString *RewardIdentifier = #"RewardTableCell";
RewardTableCell *RewardCell = (RewardTableCell *)[tableView dequeueReusableCellWithIdentifier:RewardIdentifier];
if (RewardCell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"RewardTableCell" owner:self options:nil];
RewardCell = [nib objectAtIndex:0];
}
return RewardCell ;
}
}
}
It seems to be working fine now. What I did was create boolean values to keep track of my data when my data source is nil. Like so;
[SoundCloudAPI getTracksWithSearch:userInput userID:nil withCompletion:^(NSMutableArray *tracks) {
self.searchTracks = tracks;
[self.tableView beginUpdates];
if (tracks.count) {
self.songsHeaderIsHidden = NO;
}
else
self.songsHeaderIsHidden = YES;
[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];
[[self.tableView headerViewForSection:1] setNeedsLayout];
[[self.tableView headerViewForSection:1] setNeedsDisplay];
[self.tableView endUpdates];
}];
Then set the header accordingly..
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//Create custom header titles for desired header spacing
if (section == 0) {
if (self.userHeaderIsHidden) {
return nil;
}
else {
UIView *userHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
HeaderTitleLabel *usersHeaderTitle = [[HeaderTitleLabel alloc] initWithFrame:CGRectMake(17, 10, 150, 20) headerText:#"USERS"];
[userHeaderView addSubview:usersHeaderTitle];
return userHeaderView;
}
}
else if (section == 1){
if (self.songsHeaderIsHidden) {
return nil;
}
else {
UIView *songsHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
songsHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
HeaderTitleLabel *songsHeaderTitle = [[HeaderTitleLabel alloc] initWithFrame:CGRectMake(17, 0, 150, 20) headerText:#"SONGS"];
[songsHeaderView addSubview:songsHeaderTitle];
return songsHeaderView;
}
}
else
return nil;
}
Personally, I would use UICollectionView and write your own layout. That way you can explicitly layout where the section headers will be at all times. The best approach is to probably subclass UICollectionViewFlowLayout because you get all the superclass properties for free (such as itemSize, headerReferenceSize, etc.)
Here's an implementation I wrote for having sticky headers, like the Instagram app.
Notice that in prepareLayout, I just calculate the normal positions of every element. Then in layoutAttributesForElementInRect I go through and figure out where to place the header. This is where you can go through and see if the header should be shown or not.
import UIKit
class BoardLayout: UICollectionViewFlowLayout {
private var sectionFrames: [CGRect] = []
private var headerFrames: [CGRect] = []
private var footerFrames: [CGRect] = []
private var layoutAttributes: [UICollectionViewLayoutAttributes] = []
private var contentSize: CGSize = CGSizeZero
override func prepareLayout() {
super.prepareLayout()
self.sectionFrames.removeAll(keepCapacity: false)
self.headerFrames.removeAll(keepCapacity: false)
self.footerFrames.removeAll(keepCapacity: false)
self.layoutAttributes.removeAll(keepCapacity: false)
let sections = self.collectionView?.numberOfSections()
var yOffset: CGFloat = 0.0
for var i: Int = 0; i < sections; i++ {
let indexPath = NSIndexPath(forItem: 0, inSection: i)
var itemSize: CGSize = self.itemSize
if let d = self.collectionView?.delegate as? UICollectionViewDelegateFlowLayout {
if let collection = self.collectionView {
if let size = d.collectionView?(collection, layout: self, sizeForItemAtIndexPath: NSIndexPath(forItem: 0, inSection: i)) {
itemSize = size
}
}
}
let headerFrame = CGRect(x: 0, y: yOffset, width: self.headerReferenceSize.width, height: self.headerReferenceSize.height)
self.headerFrames.append(headerFrame)
var headerAttribute = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withIndexPath: indexPath)
headerAttribute.frame = headerFrame
headerAttribute.zIndex = 1000
self.layoutAttributes.append(headerAttribute)
yOffset += self.headerReferenceSize.height - 1 // - 1 so that the bottom border of the header and top border of the cell line up
let sectionFrame = CGRect(x: 0, y: yOffset, width: itemSize.width, height: itemSize.height)
self.sectionFrames.append(sectionFrame)
var sectionAttribute = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
sectionAttribute.frame = sectionFrame
self.layoutAttributes.append(sectionAttribute)
yOffset += itemSize.height
let footerFrame = CGRect(x: 0, y: yOffset, width: self.footerReferenceSize.width, height: self.footerReferenceSize.height)
self.footerFrames.append(footerFrame)
var footerAttribute = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withIndexPath: indexPath)
footerAttribute.frame = footerFrame
self.layoutAttributes.append(footerAttribute)
yOffset += self.minimumLineSpacing + self.footerReferenceSize.height
}
self.contentSize = CGSize(width: self.collectionView!.width, height: yOffset)
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
var newAttributes: [UICollectionViewLayoutAttributes] = []
for attributes in self.layoutAttributes {
let frame = attributes.frame
if !CGRectIntersectsRect(frame, CGRect(x: 0, y: rect.origin.y, width: rect.size.width, height: rect.size.height)) {
continue
}
let indexPath = attributes.indexPath
let section = indexPath.section
if let kind = attributes.representedElementKind {
if kind == UICollectionElementKindSectionHeader {
var headerFrame = attributes.frame
let footerFrame = self.footerFrames[section]
if CGRectGetMinY(headerFrame) <= self.collectionView!.contentOffset.y {
headerFrame.origin.y = self.collectionView!.contentOffset.y
}
if CGRectGetMinY(headerFrame) >= CGRectGetMinY(footerFrame) {
headerFrame.origin.y = footerFrame.origin.y
}
attributes.frame = headerFrame
self.headerFrames[section] = headerFrame
} else if kind == UICollectionElementKindSectionFooter {
attributes.frame = self.footerFrames[section]
}
} else {
attributes.frame = self.sectionFrames[section]
}
newAttributes.append(attributes)
}
return newAttributes
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
let frame = self.sectionFrames[indexPath.item]
let attributes = super.layoutAttributesForItemAtIndexPath(indexPath)
attributes.frame = frame
return attributes
}
override func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! {
let attributes = super.layoutAttributesForSupplementaryViewOfKind(elementKind, atIndexPath: indexPath)
if elementKind == UICollectionElementKindSectionHeader {
attributes.frame = self.headerFrames[indexPath.section]
} else if elementKind == UICollectionElementKindSectionFooter {
attributes.frame = self.footerFrames[indexPath.section]
}
return attributes
}
override func collectionViewContentSize() -> CGSize {
return self.contentSize
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
}
I'd recommend using the UICollectionViewDelegateFlowLayout methods so you can dynamically determine the reference size of the header.

If no Table View results, display "No Results" on screen

I have a tableview, where sometimes there might not be any results to list, so I would like to put something up that says "no results" if there are no results (either a label or one table view cell?).
Is there an easiest way to do this?
I would try a label behind the tableview then hide one of the two based on the results, but since I'm working with a TableViewController and not a normal ViewController I'm not sure how smart or doable that is.
I'm also using Parse and subclassing as a PFQueryTableViewController:
#interface TableViewController : PFQueryTableViewController
I can provide any additional details needed, just let me know!
TableViewController Scene in Storyboard:
EDIT: Per Midhun MP, here's the code I'm using
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSInteger numOfSections = 0;
if ([self.stringArray count] > 0)
{
self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
numOfSections = 1;
//yourTableView.backgroundView = nil;
self.tableView.backgroundView = nil;
}
else
{
UILabel *noDataLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.tableView.bounds.size.width, self.tableView.bounds.size.height)];
noDataLabel.text = #"No data available";
noDataLabel.textColor = [UIColor blackColor];
noDataLabel.textAlignment = NSTextAlignmentCenter;
//yourTableView.backgroundView = noDataLabel;
//yourTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
self.tableView.backgroundView = noDataLabel;
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
return numOfSections;
}
And here's the View I'm getting, it still has separator lines. I get the feeling that this is some small change, but I'm not sure why separator lines are showing up?
You can easily achieve that by using backgroundView property of UITableView.
Objective C:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSInteger numOfSections = 0;
if (youHaveData)
{
yourTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
numOfSections = 1;
yourTableView.backgroundView = nil;
}
else
{
UILabel *noDataLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, yourTableView.bounds.size.width, yourTableView.bounds.size.height)];
noDataLabel.text = #"No data available";
noDataLabel.textColor = [UIColor blackColor];
noDataLabel.textAlignment = NSTextAlignmentCenter;
yourTableView.backgroundView = noDataLabel;
yourTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
return numOfSections;
}
Swift:
func numberOfSections(in tableView: UITableView) -> Int
{
var numOfSections: Int = 0
if youHaveData
{
tableView.separatorStyle = .singleLine
numOfSections = 1
tableView.backgroundView = nil
}
else
{
let noDataLabel: UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: tableView.bounds.size.height))
noDataLabel.text = "No data available"
noDataLabel.textColor = UIColor.black
noDataLabel.textAlignment = .center
tableView.backgroundView = noDataLabel
tableView.separatorStyle = .none
}
return numOfSections
}
Reference UITableView Class Reference
backgroundView Property
The background view of the table view.
Declaration
Swift
var backgroundView: UIView?
Objective-C
#property(nonatomic, readwrite, retain) UIView *backgroundView
Discussion
A table view’s background view is automatically resized to match the
size of the table view. This view is placed as a subview of the table
view behind all cells, header views, and footer views.
You must set this property to nil to set the background color of the
table view.
For Xcode 8.3.2 - Swift 3.1
Here is a not-so-well-known but incredibly easy way to achieve adding a "No Items" view to an empty table view that goes back to Xcode 7. I'll leave it to you control that logic that adds/removes the view to the table's background view, but here is the flow for and Xcode (8.3.2) storyboard:
Select the scene in the Storyboard that has your table view.
Drag an empty UIView to the "Scene Dock" of that scene
Add a UILabel and any constraints to the new view and then create an IBOutlet for that view
Assign that view to the tableView.backgroundView
Behold the magic!
Ultimately this works anytime you want to add a simple view to your view controller that you don't necessarily want to be displayed immediately, but that you also don't want to hand code.
Swift Version of above code :-
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
var numOfSection: NSInteger = 0
if CCompanyLogoImage.count > 0 {
self.tableView.backgroundView = nil
numOfSection = 1
} else {
var noDataLabel: UILabel = UILabel(frame: CGRectMake(0, 0, self.tableView.bounds.size.width, self.tableView.bounds.size.height))
noDataLabel.text = "No Data Available"
noDataLabel.textColor = UIColor(red: 22.0/255.0, green: 106.0/255.0, blue: 176.0/255.0, alpha: 1.0)
noDataLabel.textAlignment = NSTextAlignment.Center
self.tableView.backgroundView = noDataLabel
}
return numOfSection
}
But If you are loading Information From a JSON , you need to check whether the JSON is empty or not , therefor if you put code like this it initially shows "No data" Message then disappear. Because after the table reload data the message hide. So You can put this code where load JSON data to an array. SO :-
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func extract_json(data:NSData) {
var error: NSError?
let jsonData: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers , error: &error)
if (error == nil) {
if let jobs_list = jsonData as? NSArray
{
if jobs_list.count == 0 {
var noDataLabel: UILabel = UILabel(frame: CGRectMake(0, 0, self.tableView.bounds.size.width, self.tableView.bounds.size.height))
noDataLabel.text = "No Jobs Available"
noDataLabel.textColor = UIColor(red: 22.0/255.0, green: 106.0/255.0, blue: 176.0/255.0, alpha: 1.0)
noDataLabel.textAlignment = NSTextAlignment.Center
self.tableView.backgroundView = noDataLabel
}
for (var i = 0; i < jobs_list.count ; i++ )
{
if let jobs_obj = jobs_list[i] as? NSDictionary
{
if let vacancy_title = jobs_obj["VacancyTitle"] as? String
{
CJobTitle.append(vacancy_title)
if let vacancy_job_type = jobs_obj["VacancyJobType"] as? String
{
CJobType.append(vacancy_job_type)
if let company_name = jobs_obj["EmployerCompanyName"] as? String
{
CCompany.append(company_name)
if let company_logo_url = jobs_obj["EmployerCompanyLogo"] as? String
{
//CCompanyLogo.append("http://google.com" + company_logo_url)
let url = NSURL(string: "http://google.com" + company_logo_url )
let data = NSData(contentsOfURL:url!)
if data != nil {
CCompanyLogoImage.append(UIImage(data: data!)!)
}
if let vacancy_id = jobs_obj["VacancyID"] as? String
{
CVacancyId.append(vacancy_id)
}
}
}
}
}
}
}
}
}
do_table_refresh();
}
func do_table_refresh() {
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
return
})
}
You can try this control. Its is pretty neat. DZNEmptyDataSet
Or if I were you all I would do is
Check to see if your data array is empty
If it is empty then add one object called #"No Data" to it
Display that string in cell.textLabel.text
Easy peasy
Swift 3 (updated):
override func numberOfSections(in tableView: UITableView) -> Int {
if myArray.count > 0 {
self.tableView.backgroundView = nil
self.tableView.separatorStyle = .singleLine
return 1
}
let rect = CGRect(x: 0,
y: 0,
width: self.tableView.bounds.size.width,
height: self.tableView.bounds.size.height)
let noDataLabel: UILabel = UILabel(frame: rect)
noDataLabel.text = "Custom message."
noDataLabel.textColor = UIColor.white
noDataLabel.textAlignment = NSTextAlignment.center
self.tableView.backgroundView = noDataLabel
self.tableView.separatorStyle = .none
return 0
}
Swift3.0
I hope it server your purpose......
In your UITableViewController .
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if searchController.isActive && searchController.searchBar.text != "" {
if filteredContacts.count > 0 {
self.tableView.backgroundView = .none;
return filteredContacts.count
} else {
Helper.EmptyMessage(message: ConstantMap.NO_CONTACT_FOUND, viewController: self)
return 0
}
} else {
if contacts.count > 0 {
self.tableView.backgroundView = .none;
return contacts.count
} else {
Helper.EmptyMessage(message: ConstantMap.NO_CONTACT_FOUND, viewController: self)
return 0
}
}
}
Helper Class with function :
/* Description: This function generate alert dialog for empty message by passing message and
associated viewcontroller for that function
- Parameters:
- message: message that require for empty alert message
- viewController: selected viewcontroller at that time
*/
static func EmptyMessage(message:String, viewController:UITableViewController) {
let messageLabel = UILabel(frame: CGRect(x: 0, y: 0, width: viewController.view.bounds.size.width, height: viewController.view.bounds.size.height))
messageLabel.text = message
let bubbleColor = UIColor(red: CGFloat(57)/255, green: CGFloat(81)/255, blue: CGFloat(104)/255, alpha :1)
messageLabel.textColor = bubbleColor
messageLabel.numberOfLines = 0;
messageLabel.textAlignment = .center;
messageLabel.font = UIFont(name: "TrebuchetMS", size: 18)
messageLabel.sizeToFit()
viewController.tableView.backgroundView = messageLabel;
viewController.tableView.separatorStyle = .none;
}
I think the most elegant way to solve your problem is switching from a UITableViewController to a UIViewController that contains a UITableView. This way you can add whatever UIView you want as subviews of the main view.
I wouldn't recommend using a UITableViewCell to do this you might need to add additional things in the future and things can quicky get ugly.
You can also do something like this, but this isn't the best solution either.
UIWindow* window = [[UIApplication sharedApplication] keyWindow];
[window addSubview: OverlayView];
Use this code in Your numberOfSectionsInTableView method:-
if ([array count]==0
{
UILabel *fromLabel = [[UILabel alloc]initWithFrame:CGRectMake(50, self.view.frame.size.height/2, 300, 60)];
fromLabel.text =#"No Result";
fromLabel.baselineAdjustment = UIBaselineAdjustmentAlignBaselines;
fromLabel.backgroundColor = [UIColor clearColor];
fromLabel.textColor = [UIColor lightGrayColor];
fromLabel.textAlignment = NSTextAlignmentLeft;
[fromLabel setFont:[UIFont fontWithName:Embrima size:30.0f]];
[self.view addSubview:fromLabel];
[self.tblView setHidden:YES];
}
I would present a an overlay view that has the look and message you want if the tableview has no results. You could do it in ViewDidAppear, so you have the results before showing/not showing the view.
SWIFT 3
let noDataLabel: UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: tableView.bounds.size.height))
noDataLabel.text = "No data available"
noDataLabel.textColor = UIColor.white
noDataLabel.font = UIFont(name: "Open Sans", size: 15)
noDataLabel.textAlignment = .center
tableView.backgroundView = noDataLabel
tableView.separatorStyle = .none
If you don't use the tableview footer and do not want the tableview to fill up the screen with empty default table cells i would suggest that you set your tableview footer to an empty UIView. I do not know the correct syntax for doing this in obj-c or Swift, but in Xamarin.iOS i would do it like this:
public class ViewController : UIViewController
{
UITableView _table;
public ViewController (IntPtr handle) : base (handle)
{
}
public override void ViewWillAppear(bool animated) {
// Initialize table
_table.TableFooterView = new UIView();
}
}
Above code will result in a tableview without the empty cells
Here is the solution that worked for me.
Add the following code to a new file.
Change your table class to the custom class "MyTableView" from storyboard or .xib
(this will work for the first section only. If you want to customize more, do changes in the MyTableView reloadData() function accordingly for other sections)
public class MyTableView: UITableView {
override public func reloadData() {
super.reloadData()
if self.numberOfRows(inSection: 0) == 0 {
if self.viewWithTag(1111) == nil {
let noDataLabel = UILabel()
noDataLabel.textAlignment = .center
noDataLabel.text = "No Data Available"
noDataLabel.tag = 1111
noDataLabel.center = self.center
self.backgroundView = noDataLabel
}
} else {
if self.viewWithTag(1111) != nil {
self.backgroundView = nil
}
}
}
}
If you want to do this without any code, try this!
Click on your tableView.
Change the style from "plain" to "grouped".
Now when you use ....
tableView.backgroundView = INSERT YOUR LABEL OR VIEW
It will not show the separators!
Add this code in one file and change your collection type to CustomCollectionView
import Foundation
class CustomCollectionView: UICollectionView {
var emptyModel = EmptyMessageModel()
var emptyView: EmptyMessageView?
var showEmptyView: Bool = true
override func reloadData() {
super.reloadData()
emptyView?.removeFromSuperview()
self.backgroundView = nil
if !showEmptyView {
return
}
if numberOfSections < 1 {
let rect = CGRect(x: 0,
y: 0,
width: self.bounds.size.width,
height: self.bounds.size.height)
emptyView = EmptyMessageView()
emptyView?.frame = rect
if let emptyView = emptyView {
// self.addSubview(emptyView)
self.backgroundView = emptyView
}
emptyView?.setView(with: emptyModel)
} else {
emptyView?.removeFromSuperview()
self.backgroundView = nil
}
}
}
class EmptyMessageView: UIView {
#IBOutlet weak var messageLabel: UILabel!
#IBOutlet weak var imageView: UIImageView!
var view: UIView!
override init(frame: CGRect) {
super.init(frame: frame)
xibSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
func xibSetup() {
view = loadViewFromNib()
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(view)
}
func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: "EmptyMessageView", bundle: bundle)
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
return view
}
func setView(with model: EmptyMessageModel) {
messageLabel.text = model.message ?? ""
imageView.image = model.image ?? #imageLiteral(resourceName: "no_notification")
}
}
///////////
class EmptyMessageModel {
var message: String?
var image: UIImage?
init(message: String = "No data available", image: UIImage = #imageLiteral(resourceName: "no_notification")) {
self.message = message
self.image = image
}
}

Set height of delete button that appears on swipe in UITableViewCell

I have UITableViewCell as shown in figure below.
The cell occupy the height occupied by delete. The cell height is set so as to keep spacing between two cell.
Now, when i swipe and delete button appears (red in color), it occupies cell height as given in picture above. I simply want to set its height to height of white part only or say the height of gray button. Can anyone help me on how to set the height of delete button that appears after swipe in UITableViewCell?
The best way to solve this was overriding
-(void)layoutSubviews in YourCustomCell:UITableViewCell
then
if ([NSStringFromClass([subview class])isEqualToString:#"UITableViewCellDeleteConfirmationControl"]){
UIView *deleteButtonView = (UIView *)[subview.subviews objectAtIndex:0];
CGRect buttonFrame = deleteButtonView.frame;
buttonFrame.origin.x = Xvalue;
buttonFrame.origin.y = Yvalue;
buttonFrame.size.width = Width;
buttonFrame.size.height = Height;
deleteButtonView.frame = buttonFrame;
}
Use this code in your custom Cell class
-(void) layoutSubviews
{
NSMutableArray *subviews = [self.subviews mutableCopy];
UIView *subV = subviews[0];
if ([NSStringFromClass([subV class])isEqualToString:#"UITableViewCellDeleteConfirmationView"]){
[subviews removeObjectAtIndex:0];
CGRect f = subV.frame;
f.size.height = 106; // Here you set height of Delete button
subV.frame = f;
}
}
Swift 5, works for iOS12, iOS13 and iOS14
func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {
// for iOS13, iOS14
if let swipeContainerView = tableView.subviews.first(where: { String(describing: type(of: $0)) == "_UITableViewCellSwipeContainerView" }) {
if let swipeActionPullView = swipeContainerView.subviews.first, String(describing: type(of: swipeActionPullView)) == "UISwipeActionPullView" {
swipeActionPullView.frame.size.height -= 10
}
}
// for iOS12
tableView.subviews.forEach { subview in
if String(describing: type(of: subview)) == "UISwipeActionPullView" {
subview.frame.size.height -= 10
}
}
}
Add this method to your customCell.m file.
-(void) layoutSubviews
{
NSMutableArray *subviews = [self.subviews mutableCopy];
UIView *subview = subviews[0];
if ([NSStringFromClass([subview class])isEqualToString:#"UITableViewCellDeleteConfirmationView"]){
UIView *deleteButtonView = (UIView *)[subview.subviews objectAtIndex:0];
CGRect buttonFrame = deleteButtonView.frame;
buttonFrame.origin.x = deleteButtonView.frame.origin.x;
buttonFrame.origin.y = deleteButtonView.frame.origin.y;
buttonFrame.size.width = deleteButtonView.frame.size.width;
buttonFrame.size.height = 46;
deleteButtonView.frame = buttonFrame;
subview.frame=CGRectMake(subview.frame.origin.x, subview.frame.origin.y, subview.frame.size.width, 46);
deleteButtonView.clipsToBounds=YES;
subview.clipsToBounds=YES;
}
}
For IOS 13 , the Position has been yet again change , not inside table view it is once again in _UITableViewCellSwipeContainerView . Thus you should iterate through that as well.Take a look below
([NSStringFromClass([subview class])
isEqualToString:#"_UITableViewCellSwipeContainerView"]){
for (UIView *deleteButtonSubview in subview.subviews){
if ([NSStringFromClass([deleteButtonSubview class])
isEqualToString:#"UISwipeActionPullView"]) {
if ([NSStringFromClass([deleteButtonSubview.subviews[0] class]) isEqualToString:#"UISwipeActionStandardButton"]) {
//do what you want
}
}
}
}
Swift 5 - iOS 14
Change the way you are handling cell height to add spacing using the following:
override var frame: CGRect {
get {
return super.frame
}
set (newFrame) {
var frame = newFrame
frame.origin.y += 4
frame.size.height -= 10
super.frame = frame
}
}
Write below code in your custom cell hope it will work for you-
- (void)willTransitionToState:(UITableViewCellStateMask)state
{
[super willTransitionToState:state];
if(state == UITableViewCellStateShowingDeleteConfirmationMask)
{
[self performSelector:#selector(resetDeleteButtonSize) withObject:nil afterDelay:0];
}
}
- (void)resetDeleteButtonSize
{
NSMutableArray *subviews = [self.subviews mutableCopy];
while (subviews.count > 0)
{
UIView *subV = subviews[0];
[subviews removeObjectAtIndex:0];
if ([NSStringFromClass([subV class])isEqualToString:#"UITableViewCellDeleteConfirmationButton"])
{
CGRect f = subV.frame;
f.size.height = 74;
subV.frame = f;
break;
}
else
{
[subviews addObjectsFromArray:subV.subviews];
}
}
}
To see how it's work in IOS 11 please copy this Swift 4 code snippet in your UITableViewController:
override func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) {
self.tableView.subviews.forEach { subview in
print("YourTableViewController: \(String(describing: type(of: subview)))")
if (String(describing: type(of: subview)) == "UISwipeActionPullView") {
if (String(describing: type(of: subview.subviews[0])) == "UISwipeActionStandardButton") {
var deleteBtnFrame = subview.subviews[0].frame
deleteBtnFrame.origin.y = 12
deleteBtnFrame.size.height = 155
// Subview in this case is the whole edit View
subview.frame.origin.y = subview.frame.origin.y + 12
subview.frame.size.height = 155
subview.subviews[0].frame = deleteBtnFrame
subview.backgroundColor = UIColor.yellow
}
}
}
}
This code working for IOS 11 and higher
SWIFT
override func layoutSubviews() {
super.layoutSubviews()
for subview in self.subviews {
if String(describing: type(of: subview.self)) == "UITableViewCellDeleteConfirmationView" {
let deleteButton = subview
let deleteButtonFrame = deleteButton.frame
let newFrame = CGRect(x: deleteButtonFrame.minX,
y: deleteButtonFrame.minY,
width: deleteButtonFrame.width,
height: yourHeight)
deleteButton.frame = newFrame
}
}
}

Resources