Showing posts with label Table view related.... Show all posts
Showing posts with label Table view related.... Show all posts

11 Dec 2017

Expandable tableView Code Objective C...


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *expandTableView;

@end



#import "ViewController.h"

@interface ViewController ()
{
    NSMutableArray *mainCategory;
    NSMutableArray *subCategory;
    NSMutableArray *expandStatusArray;
}
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //Intialize the main Category
    
    self.expandTableView.sectionFooterHeight = 0;
    
    mainCategory = [[NSMutableArray alloc] initWithObjects:@"MEN",@"WOMEN",@"KIDS",@"RECHARGE", nil];//@[@"",@"",@"",@""];
    
    
    subCategory = [[NSMutableArray alloc] initWithObjects:@[@"Cloths",@"Watches",@"Footwear"],@[@"Cloths",@"Jewellery",@"Footwear",@"Bangles"],@[@"Cloths",@"Toys"],@[@"Jio",@"Bsnl",@"Airtel",@"Uninor",@"Idea",@"vodafone"], nil];
    
    expandStatusArray = [[NSMutableArray alloc] initWithObjects:@"1",@"0",@"0",@"0",nil];
    //@YES for expand the cell
    //@NO for close the cell
    
    // Do any additional setup after loading the view, typically from a nib.
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return mainCategory.count;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    NSString * status = [expandStatusArray objectAtIndex:section];

    if ([status isEqualToString:@"1"]) {
        NSArray *subArray = [subCategory objectAtIndex:section];
        return subArray.count;

    }
    return 0;
    
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellID"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellID"];
    }
    NSArray *subArray = [subCategory objectAtIndex:indexPath.section];
    NSString *dataStr = [subArray objectAtIndex:indexPath.row];
    cell.textLabel.text = dataStr;
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    //Programatically create the view
    CGRect viewFrame = CGRectMake(0, 0, tableView.frame.size.width, 50);
    UIView *headerView = [[UIView alloc] initWithFrame:viewFrame];
    headerView.backgroundColor = [UIColor colorWithRed:76.0f/255.0f green:139.0f/255.0f blue:245.0f/255.0f alpha:1.0f];
    
    //Crate label programatically
    
    UILabel *headerLbl = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 50)];
    headerLbl.text = [mainCategory objectAtIndex:section];
    headerLbl.textAlignment = NSTextAlignmentCenter;
    [headerView addSubview:headerLbl];
    
    UIButton *expandBtn = [[UIButton alloc] initWithFrame:CGRectMake(tableView.frame.size.width-50, 0, 50, 50)];
    expandBtn.titleLabel.text = @"+";
    expandBtn.backgroundColor = [UIColor redColor];
    [headerView addSubview:expandBtn];
    expandBtn.tag = section;
    
    [expandBtn addTarget:self action:@selector(expandCell:) forControlEvents:UIControlEventTouchUpInside];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

- (void)expandCell:(UIButton*)button{
    
    NSString * status = [expandStatusArray objectAtIndex:button.tag];
    
    if ([status isEqualToString:@"1"]) {
        
        //Replace with o
        [expandStatusArray replaceObjectAtIndex:button.tag withObject:@"0"];
    }else{
        //Replace with 1
        [expandStatusArray replaceObjectAtIndex:button.tag withObject:@"1"];
    }
    [_expandTableView reloadData];

}










1 Jul 2017

Custom TableView cell registerNib Code...


Custom TableView cell registerNib Code...

#import "ViewController.h"
#import "TableViewCell.h" //Custom TableViewCell class

@interface ViewController ()
@end
static NSString* const cellIdentifier = @"TableViewCellid";
@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.TableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    self.TableView.estimatedRowHeight = 44.0;
    self.TableView.rowHeight = UITableViewAutomaticDimension;
    
    self.TableView.delegate = self;
    self.TableView.dataSource = self;
    
    UINib *nib= [UINib nibWithNibName:@"TableViewCell" bundle:nil];
    [self.TableView registerNib:nib forCellReuseIdentifier:cellIdentifier];

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 10;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TableViewCell *cell = [self.TableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    


}


24 Jun 2017

TableView header customisation...


TableView header customisation...



- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @[@"Section 1",@"Section 2"] [section];
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    if([view isKindOfClass:[UITableViewHeaderFooterView class]]){
        
        UITableViewHeaderFooterView *tableViewHeaderFooterView = (UITableViewHeaderFooterView *) view;
        tableViewHeaderFooterView.textLabel.textAlignment = NSTextAlignmentCenter;
        tableViewHeaderFooterView.contentView.backgroundColor = [UIColor colorWithRed:34/255.0 green:41/255.0 blue:56/255.0 alpha:1.0];
        tableViewHeaderFooterView.textLabel.font = [UIFont fontWithName:@"Muli" size:15.0];
        tableViewHeaderFooterView.textLabel.textColor = [UIColor whiteColor];
       
    }

}

28 Apr 2017

Expand/collapse section in TableView with Section (Customized) & Row resizes depends on text in iOS...


Expand/collapse section in TableView with Section (Customized) & Row resizes depends on text in iOS...  


Result:-

 



Storyboard:-

Its an Grouped table view (make it as Grouped/Plain depends on requirement).







#import <UIKit/UIKit.h>
#import "HeaderView.h"

@interface ViewController : UIViewController<UITableViewDelegate>

@property CGFloat headerHeight;

@end


#import "ViewController.h"

@interface ViewController ()

{
    NSMutableArray *arrayForBool;
    NSArray *qnsArray;
    NSMutableArray *answersArray;
   
}

@property (weak, nonatomic) IBOutlet UITableView *expandableTableView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    arrayForBool=[[NSMutableArray alloc]init];
    
    qnsArray = [[NSArray alloc]initWithObjects:@"Lorem ipsum dolor sit amet, auctor amet velit mauris torquent vulputate, in enim vehicula morbi nunc, porta ipsum erat etiam.1",@"Justo enim. Ut volutpat. Amet lectus donec eros, neque sapien lectus elit quam pellentesque dolor. Ante pharetra dolor lectus, imperdiet erat mauris eu.2",@"ut ad quis consequat convallis. A mollis velit auctor aliquam sit, fusce tristique, dui vestibulum curabitur diamlorem nonummy vestibulum.3",@"dictumst phasellusviverra donec sit aenean.4",@"Lorem ipsum dolor sit amet, auctor amet velit mauris torquent vulputate, in enim vehicula morbi nunc, porta ipsum erat etiam..5",@"Justo enim. Ut volutpat. Amet lectus donec eros, neque sapien lectus elit quam pellentesque dolor. Ante pharetra dolor lectus, imperdiet erat mauris eu..6",@"ut ad quis consequat convallis. A mollis velit auctor aliquam sit, fusce tristique, dui vestibulum curabitur diamlorem nonummy vestibulum..7",@"dictumst phasellusviverra donec sit aenean..8", nil];
    
    for (int i=0; i<[qnsArray count]; i++) {
        [arrayForBool addObject:[NSNumber numberWithBool:NO]];
    }
    
    answersArray = [[NSMutableArray alloc]initWithObjects:@"Mattis sem rhoncus maecenas mi vel, nulla ante justo etiam sociis sit fusce, arcu porttitor, congue sed orci a cras. Nihil excepteur tempor metus metus. Non imperdiet ligula leo==>1",@" Elit consectetuer enim, vel suscipit, orci suscipit. Sit nunc, at ipsum eu aliquam feugiat, egestas cras semper ac, nulla vitae at elementum venenatis donec est, mus malesuada vel fuga felis blandit neque. Maecenas velit tempor pulvinar in,==>2",@" dapibus vivamus, aliquam elit a, fermentum aenean venenatis tristique. Ipsum suscipit, scelerisque magna ornare sodales mauris, consectetuer sed, ante faucibus proin vulputate pharetra wisi gravida, nullam eleifend aliquam. Risus pulvinar leo massa a, blandit sed bibendum, laoreet pellentesque nulla varius erat volutpat. Aliquam nam egestas.==>3",@"Vulputate duis ipsum vivamus ligula placerat metus, urna pellentesque pharetra sit ipsum eget tristique, dignissim a venenatis maecenas, hendrerit neque magnis, dui sed duis accumsan. Ridiculus suscipit vivamus.==>4",@"Mattis sem rhoncus maecenas mi vel, nulla ante justo etiam sociis sit fusce, arcu porttitor, congue sed orci a cras. Nihil excepteur tempor metus metus. Non imperdiet ligula leo>>>5",@" Elit consectetuer enim, vel suscipit, orci suscipit. Sit nunc, at ipsum eu aliquam feugiat, egestas cras semper ac, nulla vitae at elementum venenatis donec est, mus malesuada vel fuga felis blandit neque. Maecenas velit tempor pulvinar in,>>>6",@" dapibus vivamus, aliquam elit a, fermentum aenean venenatis tristique. Ipsum suscipit, scelerisque magna ornare sodales mauris, consectetuer sed, ante faucibus proin vulputate pharetra wisi gravida, nullam eleifend aliquam. Risus pulvinar leo massa a, blandit sed bibendum, laoreet pellentesque nulla varius erat volutpat. Aliquam nam egestas.>>>7",@"Vulputate duis ipsum vivamus ligula placerat metus, urna pellentesque pharetra sit ipsum eget tristique, dignissim a venenatis maecenas, hendrerit neque magnis, dui sed duis accumsan. Ridiculus suscipit vivamus.>>>8", nil];
    

    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(10,25, self.view.frame.size.width-20, 21)];
    label.text=@"Expandable Table View";
    label.backgroundColor = [UIColor purpleColor];
    label.textAlignment=NSTextAlignmentCenter;
    [self.view addSubview:label];

    _expandableTableView.estimatedRowHeight = 2;
    _expandableTableView.rowHeight = UITableViewAutomaticDimension;

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([[arrayForBool objectAtIndex:section] boolValue]) {
        return 1; // number of rows in a section give as you want
    }
    else
        return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellid=@"cell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellid];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellid];
    }
    
    BOOL manyCells  = [[arrayForBool objectAtIndex:indexPath.section] boolValue];
    
    /********** If the section supposed to be closed *******************/
    if(!manyCells)
    {
        cell.backgroundColor=[UIColor clearColor];
        
        cell.textLabel.text=@"";
    }
    /********** If the section supposed to be Opened *******************/
    else
    {
        cell.textLabel.text = [answersArray objectAtIndex:indexPath.section];
        cell.textLabel.numberOfLines = 0;
        cell.selectionStyle=UITableViewCellSelectionStyleDefault;
//        [cell setUserInteractionEnabled:NO]; // cell(row) user interaction disabled
    }
  
    return cell;
}

/*   Works when geture added to section header    */

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    /*************** Close the section, once the data is selected ***********************************/
    [arrayForBool replaceObjectAtIndex:indexPath.section withObject:[NSNumber numberWithBool:NO]];
    
    [_expandableTableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return [qnsArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    UIView *sampleView=[self customCellView:[qnsArray objectAtIndex:section]  selectedIndex:&section];
    
    return sampleView.frame.size.height;
}

-(UIView*)customCellView :(NSString *)headerStr selectedIndex:(NSInteger *)section
{
    
    UIView *mainView=[[UIView alloc]init];

    UILabel *headerLabel=[[UILabel alloc]init];
    CGRect titleRecttt=headerLabel.frame;
    titleRecttt.size.height=[self getLabelHeight:headerStr :self.expandableTableView.frame.size.width-80 :[UIFont systemFontOfSize:18.0]].height;
    headerLabel.frame=titleRecttt;
    headerLabel.numberOfLines=0;
    headerLabel.textColor=[UIColor lightGrayColor];
    
    CGRect mainRect=mainView.frame;
    mainRect.size.height = headerLabel.frame.size.height+20;
    mainView.frame=mainRect;
    [mainView addSubview:headerLabel];
    
    UIView *myView=[[UIView alloc]initWithFrame:CGRectMake(0,0,self.expandableTableView.frame.size.width,mainView.frame.size.height)];
    [myView addSubview:mainView];
    
    return myView;
}

-(CGSize)getLabelHeight:(NSString*)text :(CGFloat)width :(UIFont*)font
{
    NSAttributedString *attributedText;
    CGRect emptyrect;
    CGSize emptysize= emptyrect.size;
    
    if (text.length>0)
    {
        attributedText =
        [[NSAttributedString alloc]
         initWithString:text
         attributes:@
         {
         NSFontAttributeName: font
         }];
        
        CGRect rect = [attributedText boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX)
                                                   options:NSStringDrawingUsesLineFragmentOrigin
                                                   context:nil];
        CGSize size = rect.size;
        return size;
    }
    return emptysize;
}


#pragma mark - Creating View for TableView Section

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    /********** Add UITapGestureRecognizer to SectionView   **************/
    
UITapGestureRecognizer  *headerTapped   = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sectionHeaderTapped:)];

    HeaderView *hView = [[HeaderView alloc]init];
   
    hView.headerLbl.backgroundColor = [UIColor yellowColor];
   
    hView.headerLbl.text = [qnsArray objectAtIndex:section];
    hView.headerLbl.numberOfLines = 0;
    
    hView.headerLbl.lineBreakModeNSLineBreakByWordWrapping;
    
    [hView addGestureRecognizer:headerTapped]; /***  add gesture to header  ***/
    hView.tag=section;
    
    return  hView;
}

#pragma mark - Table header gesture tapped

- (void)sectionHeaderTapped:(UITapGestureRecognizer *)gestureRecognizer {
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:gestureRecognizer.view.tag];
    if (indexPath.row == 0) {
        BOOL collapsed  = [[arrayForBool objectAtIndex:indexPath.section] boolValue];
        for (int i=0; i<[qnsArray count]; i++) {
            if (indexPath.section==i) {
                [arrayForBool replaceObjectAtIndex:i withObject:[NSNumber numberWithBool:!collapsed]];
            }
        }
        [_expandableTableView reloadSections:[NSIndexSet indexSetWithIndex:gestureRecognizer.view.tag] withRowAnimation:UITableViewRowAnimationAutomatic];
    }

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end




#import <UIKit/UIKit.h>

@interface HeaderView : UIView

@property (weak, nonatomic) IBOutlet UIView *bgview;

@property (weak, nonatomic) IBOutlet UILabel *headerLbl;
@end



#import "HeaderView.h"

#import "ViewController.h"



@implementation HeaderView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (id)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    
    if (self) {
        [self setup];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    
    self = [super initWithCoder:aDecoder];
    
    if (self) {
        [self setup];
    }
    return self;
}

-(void)setup{
    
    if (self.subviews.count == 0)
    {
        HeaderView *viewFromNib = [[NSBundle mainBundle] loadNibNamed:@"HeaderView" owner:self options:nil].firstObject;
        _bgview = viewFromNib.bgview;
        self.headerLbl = viewFromNib.headerLbl;
        [viewFromNib setFrame:self.bounds];
        [viewFromNib setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
        [self addSubview:viewFromNib];
        
    }
}

@end




HeaderView.xib:-









Recent Posts

Codable demo

Link: https://www.dropbox.com/s/kw7c1kgv1628bh7/codableDemo.zip?dl=0