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).
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:§ion];
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.lineBreakMode = NSLineBreakByWordWrapping;
[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:-
No comments:
Post a Comment