I am new to iOS Programming, I have implemented UITableviewController. I placed UIView inside of UITableView. I designed label, textfields and tableview inside of UIView. Here My problem is, When I increasing the dynamic tableview based on array count, I want to increase my UIView height also. I don't know how to do that?? Below is my design structure,
UITableViewController---
UIView----- (1)
Label---Label (2)
label---Label (3)
label--- (4)
UItableview (5)
textfield (6)
textfield (7)
and so on
below I have successfully increase the (5) height and also I want to increase (1) height I don't know how to do?? can any one suggest solution for this?? I have tried this below code.
-(void)viewDidLayoutSubviews{
CGFloat numberofrows=creditList.count;
height = numberofrows*propertytable.rowHeight;
_tableviewheight.constant = height;
propertytable.frame =CGRectMake(propertytable.frame.origin.x,propertytable.frame.origin.y, propertytable.frame.size.width,_tableviewheight.constant);
CGRect myviewframe=mainview.frame;
NSLog(#"The myviewframe value is %f",myviewframe.size.height);
mainview.translatesAutoresizingMaskIntoConstraints=YES;
myviewframe.size.height=5000;
mainview.frame=myviewframe;
mainview.frame = CGRectMake(0,0,mainview.frame.size.width, 5000);
mainview.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
mainview.contentMode = UIViewContentModeScaleAspectFit;
[mainview layoutIfNeeded];
}
If object has autolayout, try this:
- (void)viewDidLoad {
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 105; //Default Height
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewAutomaticDimension;
}
Related
A self-sizing UITableViewCell: MyTableViewCell.m
-(void) viewDidLoad{
UIView *sample = [[UIView alloc] init];
[self.contentView addSubview: sample];
//Fake code here. Let sample view fill the whole contentView:
Constraint1: sample.leading = contentView.leading;
Constraint2: sample.trailing = contentView.trailing;
Constraint3: sample.top = contentView.top;
Constraint4: sample.bottom = contentView.bottom;
Constraint5: sample.height = 20;
NSLayoutConstraint:activateConstriant(constraints 1-5);
}
This code works and the MyTableViewCell has a height of 20.
However, I want to change the height at run time (after this cell added to a UITableView), so I add a new method to MyTableViewCell.m
-(void) updateHeight:(CGFloat)newHeight{
//Fake code here. change the constant of constraint1
Constraint1 = get reference of Constraint1 in viewDidLoad();
Constraint1.constant = newHeight
}
I run the code and call updateHeight:10 and got the log warning:
2017-03-16 16:23:11.102858 [14541:568021] [LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"",
"",
"",
""
)
Will attempt to recover by breaking constraint
My own opinion is that my constraints created at viewDidLoad automatically creates couple of other constraints like contentView.height=20 and my change to the original constraints conflict with the constraints created by system.
I tested to change the leading of sample view instead of the height in updateHeight:, and it works! Because the change of leading doesn't affect contentView's own height constraint?
How am I supposed to do a dynamically change to auto layout like this case?
Thank you~~~
To have dynamic cell size you need to implement the below methods
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return <your estimated cell height>;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewAutomaticDimension;
}
Set the tableview row height in your view controller. Refer the following code line :
self.tableView.rowHeight = UITableViewAutomaticDimension;
Make sure your updateHeight: method executed before cell's layoutSubviews. Because if cells has been loaded, you have to reload the tableView to make your new constraints effective, so you can figure out your automatic constraints in tableView:cellForRowAtIndexPath: method, or the following code is what you need.
[tableView beginUpdates];
// your code, alter your cell's constraints here
[tableView endUpdates];
tableView.estimatedRowHeight = 44.0 //put as per your cell row height
tableView.rowHeight = UITableViewAutomaticDimension
Give Top,Bottom,Leading,Trailing Contraints to UILabel used.
Be sure numberOfLine for your UILabel in the cell is set to 0.
Estimated row height needs to be provided.(Provide any appropriate value)
I ran into this issue today and solved it by overriding the UITableViewCell object's drawRect method.
- (void) drawRect:(CGRect)rect {
[super drawRect:rect];
[self adjustConstraint];
}
This question already has answers here:
Using Auto Layout in UITableView for dynamic cell layouts & variable row heights
(28 answers)
Closed 6 years ago.
Hi in my application i have a requirement to display prodcuts with description in tablview. For achieving this i added two satckviews on tablview cell content view. Both stackviews holds labels and one label have a prodcut name and another one have description. At app launch the app cell height is 100 by default, but when ever i select cell i want to show complete description in cell along with product name i mean need to change cell height.Can anyone please let help me how to achieve this.How to change cell height dynamically. Please help me.
I tried below approach it shows more description in stack view label but cell height is not getting change. So unable to see total description.
cell.productDescription.numberOfLines=50;
cell.productDescription.lineBreakMode=NSLineBreakByCharWrapping;
Best way to use Constraint for your application. So you don't have to manage heighforCell. If you are going to coding part then you have to find out height of text and then you need to set in heightForRowAtIndexPath method.
Here is the code to get height from string:
-(float )getHeightForText : (NSString *)strText
{
UILabel *lbl = [[UILabel alloc] init];
CGRect rect;
rect.origin = CGPointZero;
float width = YOUR_LABEL_WIDHT
rect.size = CGSizeMake(width, 3000);
lbl.font = MESSAGE_TEXT_FONT;
lbl.frame = rect;
lbl.text = strText;
lbl.numberOfLines = 1000;
[lbl sizeToFit];
float height = lbl.frame.size.height;
return height;
}
Write below code in your heightForRowAtIndexPath method:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [self getHeightForText:YOUR_TEXT];
}
Use UITableViewDelegate Method
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
Currently, I've developed project that UIScrollView, UITableView, another 3 more UIView inputs and UIButton at the last. In that page, UIScrollView height will be dynamically increased based on height of UITableView.
For UITableView there is no more scrolling. Its height will be increased as well based on how many rows are added based on JSON data loaded by Async as follow.
productHeight = 44;
productHeight *= _nsOrderItems.count;
productHeight = productHeight + 100;
if (isHeaderTap) {
self.productTableHeight.constant = 50;
} else {
self.productTableHeight.constant = productHeight;
}
//then the tableView must be redrawn
[self.productTable setNeedsDisplay];
My Problem is I want to increase height of UIScrollView based on height of UITableView.
- (void)viewDidLayoutSubviews {
[self.scrollView setContentSize:CGSizeMake(_scrollView.frame.size.width, _btnEdit.frame.origin.y + _btnEdit.frame.size.height)];
}
You can definitely do that,
First make sure your constraint of cells subView must set to top to bottom in order to calculate the height required for the cell.
Make sure your delegated are set as below
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 44;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewAutomaticDimension;
}
Set height constraint of your tableView and make outlet of that constraint.
Add below method to your class where you want to resize your tableView dynamically.
- (void)adjustHeightOfTableview
{
CGFloat height = self.tableView.contentSize.height;
//CGFloat maxHeight = self.tableView.superview.frame.size.height - self.tableView.frame.origin.y;
/*
Here you have to take care of two things, if there is only tableView on the screen then you have to see is your tableView going below screen using maxHeight and your screen height,
Or you can add your tableView inside scrollView so that your tableView can increase its height as much it requires based on the number of cell (with different height based on content) it has to display.
*/
// now set the height constraint accordingly
self.constraintHeightTableView.constant = height;
//If you want to increase tableView height with animation you can do that as below.
[UIView animateWithDuration:0.5 animations:^{
[self.view layoutIfNeeded];
}];
}
Call this method when you are ready with the dataSource for the table, and call the method as
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
//In my case i had to call this method after some delay, because (i think) it will allow tableView to reload completely and then calculate the height required for itself. (This might be a workaround, but it worked for me)
[self performSelector:#selector(adjustHeightOfTableview) withObject:nil afterDelay:0.3];
});
// Get the supposed to be height of tableview
CGFloat height = self.tableViewMenu.contentSize.height;
// get the height constraint of tableview and give it you respected height
self.constraintHeightTableView.constant = height;
// set the scroll
NOTE:- don't forget to disenable the scrolling of table from storyboard or programmatically
self.scrollView.contentSize = CGSizeMake(self.scrollView.contentSize.width, self.viewUserLogin.frame.size.height + height);
[self.scrollView layoutIfNeeded];
I am trying to set height of UILabel dynamically in the UITableView. During the launch height update is not reflected but as soon as I scroll down and scroll up back, update can be seen.
At Launch
After Scroll down and Scrolling back up again - This what I need. See the change in text in front of player icon. I need the complete text at launch itself.
Here is the code that I am trying to use:
- (void) updateMessageTextForRow:(long)row ofCell:(ESGameStreamCellView *)cell
{
NSString *item = _gameFeedItems[row];
NSString *title = item ?: NSLocalizedString(#"[No Title]", nil);
cell.message.preferredMaxLayoutWidth = cell.message.bounds.size.width;
// Update message label height
CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);
CGSize expectedLabelSize = [title sizeWithFont:cell.message.font
constrainedToSize:maximumLabelSize
lineBreakMode:cell.message.lineBreakMode];
//adjust the label the the new height.
CGRect newFrame = cell.message.frame;
newFrame.size.height = expectedLabelSize.height;
cell.message.frame = newFrame;
NSLog(#"Message = %#, Height: %f", title, cell.message.frame.size.height);
}
During Custom TableCellView Initialization
- (void)awakeFromNib {
// Initialization code
self.backgroundColor = [UIColor clearColor];
_message.lineBreakMode = NSLineBreakByWordWrapping;
_message.numberOfLines = 0;
}
Code for the row height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// Currently fixed height. Will be calculating dynamic height after adjusting the views.
return 300;
}
Are you using autoLayout ? I highly suspect that your constraints aren't set up properly: the UIImageView top should by tied with the titleLabel's bottom.
Also, you should use the new property for dynamic row : rowHeight and estimatedRowHeight.
You are getting the correct height after the cell's reuse : set the preferredMaxLayoutWidth property in the viewDidLayoutSubviews inside your custom cell class.
firstly, you should understand of the working flow of tableview delegate in objective c. Your cell height & position will be fixed after init. that's why you have to define each row's height in
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// Currently fixed height. Will be calculating dynamic height after adjusting the views.
return 300;
}
From this point forward, your cell's height will be fixed, even if you re-config the frame.
The best practice is some article called "Dynamic height tableview cell" and you can easily find it here
http://www.raywenderlich.com/87975/dynamic-table-view-cell-height-ios-8-swift
I learn on above article (thanks for Joshua Greene) and re-write it to another library allow you to make a dynamic tableview easily. You can find it here
https://github.com/EugeneNguyen/XBMobile
it's not too perfect, but hope that if can help.
I have used the following code to dynamically change the row height in ios. But the height is too high. I dont know where i made mistake. My code is as follows:
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(!self.customCell){
self.customCell = [self.goalDetailsTableview dequeueReusableCellWithIdentifier:#"GoalDetailsCell"];
}
NSMutableDictionary *cellData = [self.databaseCall transactionFromDatabase:indexPath.row goalId:self.goalId andStageId:self.stageId];
//Cell Layout
self.customCell.tipsDescription.text = [cellData objectForKey:#"tipsDescription"];
[self.customCell.tipsDescription sizeToFit];
//Height of cell
float height = (CGRectGetMaxY(self.customCell.tipsDescription.frame) + 20);
return height;
}
Note: tipsDescription is a UILabel inside the UIView which is kept inside the UITableViewCell.
You need to calculate your text height and based on it have to set cell height (yes, its going to be little mind expensive but at last you'll be happy!). Here's the one solution for this, Replacement for deprecated sizeWithFont: in iOS 7? and if you want some more info, Calculating number of lines of dynamic UILabel (iOS7) and this too UITableViewCell with UITextView height in iOS 7? (I know its not for UITextView but you can consider it with UILabel).
With iOS 8 we have self sizing table view cells. With it, there is no need to even implement heightForAtIndexPath.
Step 1) Set up constraints for your table cell
Step 2) In viewDidLoad:
self.tableView.estimatedRowHeight = 100.0; //or whatever value you need
self.tableView.rowHeight = UITableViewAutomaticDimension;
And that's it. I would also mention a few of us have ran into an issue where you might need to reload the table view's data in viewDidAppear.