How to increase the UITableView row height dynamically in ios? - ios

I have an requirement like the UITableview row height has to increase dynamically when i add more data..Like
_quoteArray = [#[#"For the past 33 years, I have looked in the mirror every morning and asked myself: 'If today were the last day of my life, would I want to do what I am about to do today?' And whenever the answer has been 'No' for too many days in a row, I know I need to change something. -Steve Jobs",
#"Be a yardstick of quality. Some people aren't used to an environment where excellence is expected. - Steve Jobs",
#"Innovation distinguishes between a leader and a follower. -Steve Jobs"]];
I wrote the code like…..
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *simpleTableIdentifier = #"NotificationCell";
MyNotificationCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
//cell.dateLabel.text =dateDisplayStr;
cell.teacherChangeLabel.text = _quoteArray[quoteIndex];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// Calculate a height based on a cell
static NSString *simpleTableIdentifier = #"NotificationCell";
MyNotificationCell *cell = [self.NotificationTableview dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if(!cell) {
cell = [self.NotificationTableview dequeueReusableCellWithIdentifier:#"CustomCell"];
}
// Configure the cell
int quoteIndex = indexPath.row % [quoteArray count];
cell.teacherChangeLabel.text = quoteArray[quoteIndex];
// Layout the cell
[cell setNeedsLayout];
// Get the height for the cell
CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
// Padding of 1 point (cell separator)
CGFloat separatorHeight = 1;
return height + separatorHeight;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 140;
}
But it is not increasing the row height if I add extra data.I don’t know where I did mistake.Can anyone please help me in this

If you want to change based on the size of the string just do it like this:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *text = [yourStringArray objectAtIndex:indexPath.row];
UIFont *font = theFontSizeYourWant;
return [self heigthWithString:text andFont:font]+30//put the +30 for personal like;
}
- (CGFloat)heigthWithString:(NSString*)string andFont:(UIFont *)font
{
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:string];
[attrStr addAttribute:NSFontAttributeName
value:font
range:NSMakeRange(0, [attrStr length])];
CGRect rect = [attrStr boundingRectWithSize:CGSizeMake(250, CGFLOAT_MAX)
options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
context:nil];
return rect.size.height;
}
Hope this helps!

Use
- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// Change the height of cell based on indexpath ForEg
if([indexPath row]==0){
return 44;
}
return 140;
}
to change the height of a cell.

If you need to support iOS7 and there are lots of items affecting the height.
As there are lots of items(or some dynamic size items), the height is not easy to calculate.
I would call a protocol method to update the height.
Pos:
Easy to change the height
No annoying calculation
Cons:
memory consumption
you may see the UITableView updating.
#property (strong, nonatomic) NSMutableArray *loadedCellHeight;
#pragma CellDelegate Methods
- (void)displayHeight:(NSString*)height atIndexPath:(NSIndexPath *)indexPath
{
NSPredicate *filter = [NSPredicate predicateWithFormat:#"indexPath == %#", indexPath];
NSArray *filteredArray = [self.loadedHeight filteredArrayUsingPredicate:filter];
if (filteredArray.count==0) {
[self.loadedAdHeight addObject:#{#"indexPath": indexPath, #"height": height}];
[self.tableView beginUpdates];
[self.tableView endUpdates];
} else {
NSDictionary *originalDict = filteredArray[0];
if ([[originalDict objectForKey:#"height"] floatValue] != [height floatValue]) {
[_loadedCellHeight removeObject:originalDict];
[_loadedCellHeight addObject:#{#"indexPath": indexPath, #"height": height}];
[self.tableView beginUpdates];
[self.tableView endUpdates];
}
}
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *dict = [self.dataArray objectAtIndex:indexPath.row];
NSPredicate *filter = [NSPredicate predicateWithFormat:#"indexPath == %#", indexPath];
NSArray *filteredArray = [self.loadedAdHeight filteredArrayUsingPredicate:filter];
if (filteredArray.count>0) {
return [filteredArray[0][#"height"] floatValue];
}
return 0;
}
What I did in my Cell(there is a webview inside it):
- (void)loadAd:(NSString*)path
{
if (_loaded) {
return;
}
NSString *encodeUrl = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
self.url = encodeUrl;
[self.webView setScalesPageToFit:YES];
self.webView.contentMode = UIViewContentModeScaleAspectFit;
self.webView.delegate = self;
self.webView.scrollView.bounces = NO;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:encodeUrl]];
[self.webView loadRequest:request];
}
-(void)parseHtml
{
NSString *html = [self.webView stringByEvaluatingJavaScriptFromString: #"document.body.innerHTML"];
NSLog(#"html:%#", html);
NSDictionary *dict = [NSDictionary dictionaryWithXMLString:html];
NSLog(#"parsed html:%#", [dict description]);
NSDictionary *heightDict = [dict dictionaryValueForKeyPath:#"img.hidden"];
NSLog(#"%#", [heightDict valueForKeyPath:#"_value"]);
NSString *heightStr = [heightDict valueForKeyPath:#"_value"];
NSString *height = [heightStr stringByReplacingOccurrencesOfString:#"advheight:" withString:#""] ;
if (self.delegate && !_loaded) {
[self.delegate displayHeight:height atIndexPath:_indexPath];
_loaded = YES;
}
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
[self parseHtml];
}

Related

how to Change the custom tableview cell height and a textview height according to its content in textview

i have created a custom cell with a textview. I need to expand the height of the textview and the height of the custom cell according to the content in the textview without using auto layout. can any one help me
This is the code:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 80;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return sendername.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier1 = #"MenuCtrl";
tsecureMsgConCell *cell = [tabVieConv dequeueReusableCellWithIdentifier:CellIdentifier1];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"MsgConCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.userName.text = [sendername objectAtIndex:indexPath.row];
cell.msgContentTxView.text = [msgContents objectAtIndex:indexPath.row];
NSString * sentDateCell = [msgSenddate objectAtIndex:indexPath.row];
NSString * replyDateCell = [msgRevidate objectAtIndex:indexPath.row];
thredIdCell = [TSecureMsgId objectAtIndex:indexPath.row];
if ([sentDateCell isEqualToString:#"NULL"])
{
cell.dateLbl.text = [msgRevidate objectAtIndex:indexPath.row];
cell.timeLbl.text = [msgRecTime objectAtIndex:indexPath.row];
cell.imgVew.image = [UIImage imageNamed:#"recive.png"];
}
else if ([replyDateCell isEqualToString:#"NULL"])
{
cell.dateLbl.text = [msgSenddate objectAtIndex:indexPath.row];
cell.timeLbl.text = [msgSendTime objectAtIndex:indexPath.row];
cell.imgVew.image = [UIImage imageNamed:#"sent.png"];
}
return cell;
}
msgContentTxView - is my textview
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = indexPath.row;
if (row != NSNotFound)
{
if ([exapmlestring length] > 0)
{
CGFloat padding = 17.0f;
CGFloat labelWidth = self.tableview.bounds.size.width - padding*2;
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:#"HelveticaNeue" size:17.0], NSFontAttributeName,
nil];
NSAttributedString *text = [[NSAttributedString alloc] initWithString:exapmlestring attributes:attributesDictionary];
NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin;
///size
CGRect boundingRect = [text boundingRectWithSize:CGSizeMake(labelWidth, CGFLOAT_MAX)
options:options
context:nil];
boundingRect.size.height = boundingRect.size.height + 100;
return (CGFloat) (ceil(boundingRect.size.height) + padding*2);
}
}
return 0;
}

how to add rss image on UITableViewCell

I am using the following code to load the RSS feed. May I know how can i add a small image from the RSS to the left hand side of the UITableViewCell? Many Thanks
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [stories count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier];
}
// Set up the cell
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
[cell setText:[[stories objectAtIndex: storyIndex] objectForKey: #"title"]];
cell.textLabel.font = [UIFont fontWithName:#"Heiti TC Light" size:16.0];
cell.textColor=[UIColor blackColor];//according to you.
cell.textLabel.numberOfLines = 3;
cell.backgroundColor = [UIColor clearColor];
self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"white.jpg"]];
self.tableView.backgroundColor = [UIColor clearColor];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
NSString * storyLink = [[stories objectAtIndex: storyIndex] objectForKey: #"link"];
// clean up the link - get rid of spaces, returns, and tabs...
storyLink = [storyLink stringByReplacingOccurrencesOfString:#" " withString:#""];
storyLink = [storyLink stringByReplacingOccurrencesOfString:#"\n" withString:#""];
storyLink = [storyLink stringByReplacingOccurrencesOfString:#" " withString:#""];
NSLog(#"link: %#", storyLink);
// open in Safari
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:storyLink]];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if ([stories count] == 0) {
NSString * path = #"http://www.medworm.com/rss/medicalfeeds/source/Nature.xml";
[self parseXMLFileAtURL:path];
}
cellSize = CGSizeMake([newsTable bounds].size.width, 60);
}
I hope this will be helpful.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyIdentifier];
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(12, 5, 158/2, 99/2) ];
//SDWebImage Extension
[imgView setImageWithURL:[NSURL URLWithString:#"http://www.yoururl.com/yourimage.jpg"] placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
[self.contentView addSubview:imgView];
}
return cell;
}

UISearchDisplayController / UISearchResultsTableView Adding in Extra Line with Each Search ? iOS7

I have a UISearchDisplayController which is behaving strangely under iOS7. The first time I do a search, everything is ok and the UISearchResultsTableView displays the results correctly.
The problem is that the second time I do a search (after dismissing the table), a blank line (looks like a cell) is added to the top of the search results table :
Each subsequent search then adds in another blank line to the top of the table, and so on and so on.
Here is the code :
//Setup the search bar.
searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0.0f, 0.0f, 360.0f, 44.0f)];
UIBarButtonItem * searchBarButton = [[UIBarButtonItem alloc] initWithCustomView:searchBar];
searchBar.delegate = self;
controller = [[UISearchDisplayController alloc]initWithSearchBar:self.searchBar contentsController:self];
controller.searchResultsDataSource = self;
controller.searchResultsDelegate = self;
self.tabBarController.navigationItem.rightBarButtonItems = #[searchBarButton];
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
if (isLoading) {
return;
}
[self filter : searchText];
[controller.searchResultsTableView reloadData];
}
- (void)filter : (NSString *)text {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"(name CONTAINS[cd] %# OR number CONTAINS[cd] %#)", text, text];
searchResults = [standArray filteredArrayUsingPredicate:predicate];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [searchResults count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyIdentifier"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"MyIdentifier"];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
if ([searchResults count] ==0) {
cell.textLabel.text = #"";
}
else {
NSString * name = [[searchResults objectAtIndex:indexPath.row] name];
NSString * number = [[searchResults objectAtIndex:indexPath.row] number];
NSString * resultsString = [NSString stringWithFormat:#"%# %#", name, number];
cell.textLabel.text = resultsString;
}
return cell;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
NSString * name = [[searchResults objectAtIndex:indexPath.row] name];
Object * exhibitor = [self getExhibitorForStandName:standName];
if ([exhibitor.companyName isEqualToString:standName]) {
NSString * status = [[self getExhibitorForStandName:standName] status];
cell.backgroundColor = [standColourMapping objectForKey:status];
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.searchDisplayController setActive:NO animated:YES];
...
}
}
Ok for future travellers, this looks like a weird bug whereby the height of the UISearchBar is added to the top of the searchResultsTable each subsequent time it appears.
The solution is the following :
controller.searchResultsTableView.contentInset = UIEdgeInsetsMake(0.0f, 0.f, 0.f, 0.f); //Fix for weird weird iOS7 bug where each subsequent
//search adds the height of the searchBar to the top of the searchResultsTableView.

UISearchBar misses elements in the non-visible part of the tableView

I have a TableView with many rows, most are not visible at the time of loading viewController. The rows of UITableView are extracted from a SQLite database. How can I make do that the SearchBar search between all rows and not just the visible ones?
In header file:
#interface ExhibitorsViewController : UIViewController <UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate>{
BOOL isSearchOn;
BOOL canSelectRow;
NSMutableArray * listOfExpositors;
NSMutableArray * searchResult;
}
//....
#end
In implementation file
-(NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
if(isSearchOn){
return [searchResult count];
//In this array there are the elements after use of searchBar
}else{
int number=[self.mutableArray count];
//In this array there are all elements of database, extracts in viewDidLoad()
return number;
}
}
- (UITableViewCell *)tableView:(UITableView *)aTableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] ;
}
if(isSearchOn){
NSString * cellValue = [searchResult objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
}else{
//loading data from the database
Database *currow =[self.mutableArray objectAtIndex:indexPath.row];
cell.textLabel.text = currow.name;
[listOfExpositors addObject:cell.textLabel.text];
//here only loads the list of names visible and not the entire table
//How do I put all the elements in this array?
NSLog(#" %#", listOfExpositors);
isSearchOn = NO;
canSelectRow = YES;
}
}
-(void) doneSearching{
isSearchOn = NO;
canSelectRow = YES;
self.tableView.scrollEnabled = YES;
[self.searchBar resignFirstResponder];
[self.tableView reloadData];
}
-(void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
isSearchOn = YES;
if(self.searchBar.text.length>0){
canSelectRow=YES;
self.tableView.scrollEnabled = YES;
}else{
canSelectRow= NO;
self.tableView.scrollEnabled = NO;
}
}
-(void) searchExpositorsTableView{
[searchResult removeAllObjects];
for (NSString *str in listOfExpositors){
NSRange titleResultsRange = [str rangeOfString:self.searchBar.text options:
NSCaseInsensitiveSearch];;
if (titleResultsRange.length >0) {
[searchResult addObject:str];
}
}
NSLog(#"%#", searchResult);
}
-(void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
if([searchText length]>0){
canSelectRow = YES;
self.tableView.scrollEnabled = YES;
[self searchExpositorsTableView];
}else{
canSelectRow = NO;
self.tableView.scrollEnabled = NO;
}
[self.tableView reloadData];
}
-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar{
[self searchExpositorsTableView];
[self.searchBar resignFirstResponder];
}
-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if(canSelectRow){
return indexPath;
}else{
return nil;
}
NSLog(#"%d", indexPath.row);
}
It was wrong to use the array created in cellForRowAtIndexPath because it was limited only to the visible elements. I then used the NSMutableArray created in viewDidLoad () that does contain all the elements of the database. I changed the following methods:
- (UITableViewCell *)tableView:(UITableView *)aTableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//....
if(isSearchOn){
NSString * cellValue = [searchResult objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
}else{
Database *currow =[self.mutableArray objectAtIndex:indexPath.row];
cell.textLabel.text = currow.name;
//Should be removed this array and used to another, self.mutableArray
//[listOfExpositors addObject:cell.textLabel.text];
// NSLog(#" %#", listOfExpositors);
isSearchOn = NO;
canSelectRow = YES;
}
}
Method for research
-(void) searchExpositorsTableView{
[searchResult removeAllObjects];
for (Database *currow in self.mutableArray){
/*In self.mutableArray there are all elements because is created in
viewDidLoad*/
NSLog(#"list of expositors %#", self.mutableArray);
NSRange titleResultsRange = [currow.name rangeOfString:self.searchBar.text options: NSCaseInsensitiveSearch];
if (titleResultsRange.length >0) {
[searchResult addObject:currow.name];
}
}
NSLog(#"%#", searchResult);
}

How To Change UITableView Cell Height Equally & Show detailedTextLabel?

Hi I have this code here.
- (void)viewDidLoad
{
[super viewDidLoad];
jsonURL = [NSURL URLWithString:#"http://oo.mu/json2.php"];
jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL usedEncoding:nil error:nil];
self.jsonArray = [jsonData JSONValue];
// Do any additional setup after loading the view, typically from a nib.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [jsonArray count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [indexPath row] * 20;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [[self.jsonArray objectAtIndex:indexPath.row] objectForKey:#"Name"];
return cell;
}
What I want is:
To change the height of the UITableView cell so I can fit more
things under the textLabel. (Currently, when I use the previous
code to increase the height of the UITableView cell, each cell
goes from big to small in different sizes).
To show under the textLabel.text a detailedTextLabel of
something else under it.
How would I do that?
I tried:
cell.textLabel.text = [[self.jsonArray objectAtIndex:indexPath.row] objectForKey:#"Name"];
cell.detailTextLabel.text = [[self.jsonArray objectAtIndex:indexPath.row] objectForKey:#"Street"];
cell.detailTextLabel.text = [[self.jsonArray objectAtIndex:indexPath.row] objectForKey:#"City"];
But it doesn't show up.
You can create new UItableview cell with the dimensions as per your requirements. Later
-(Uitableview) cellForIndexPath {
//add the customized Uitableviewcell.
}
In this way you can create the tableview cell as per your requirements. I hope it will help.

Resources