I am designing an app which has a scroll view and over it a content view having a table view with scrolling disabled . Now I want that the table view would increase its size dynamically as per my array contents. I have did some coding and I am putting my constraints screen shot so as to make things more clear -
My constraint list -
Now here is my code to populate the table view & increase its size to the content view-
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableview.dequeueReusableCellWithIdentifier("cellreuse", forIndexPath: indexPath)
cell.textLabel?.text = name[indexPath.row]
tableview.frame.size = tableview.contentSize
return cell
}
here is my main story board screenshot
So now when I run my code the content size is not increased as per my table view's size. So here is how it looks like on a 4s -
So how to also adjust my content view as per the increased height of table view dynamically supporting all constraints laid out in IB?
Follow these instructions.
Constraints Required: -
MainView to ScrollView - leading = 0, trailing = 0, top = 0, bottom = 0;
ScrollView to ContentView - leading = 0, trailing = 0, top = 0, bottom = 0, contentView.width = mainView.width, contentView.height = "Some constant"
ContentView to TableView - leading = 8, trailing = 8, top = 518(as per your screenshot), bottom = 64;
Now you need to create an IBOutlet for the height constraint of contentView, which we have given a random constant value earlier; let's call it contentViewHeightConstraint.
Now once you got the records in your array you need to call reloadData and increase the height of contentView as per the number of records in your table.
contentViewHeightConstraint.constant = 518 + 44*(name.count) + 64;
Also remove the code that you have in cellForRowAtIndexPath: for setting the size of tableView.
if arrayForOfferTable.count <= 6{
//offertableheight.constant = CGFloat( 400)
offertableheight.constant = CGFloat( 46*arrayForOfferTable.count + 40)
}
make your tableview height constraint outlet from storyboard and u can change the height of table view dynamically like me here 46 is the cell height and arrayForOfferTable.cont
Related
I have a UIView which contains a label, a button, and a UITableView which populates its data dynamically from a server. I am having trouble resizing the parent UIView to fit its content after the content has dynamically populated. For the purpose of demonstrating my issue, I have made the background of the containing UIView blue.
After populating the TableView with data, the UIView's height does not adjust causing the Tableview data to overflow, seen in the diagram below.
I have set the bottom, leading and trailing space constraints of the TableView to the superview, and top space constraint to the button. The UIView itself has no height constraints set.
I implemented a function to manually recalculate the height of the UIView after populating the content of the TableView. Code for the function below:
func resizeToFitSubviews()
{
var w: CGFloat = self.frame.size.width,
h: CGFloat = 0
for view in subviews {
if view.frame.origin.y + view.frame.height > h { h = view.frame.origin.y + view.frame.height }
}
self.frame.size = CGSize(width: w, height: h)
}
This function works. The UIView resizes to what seems to be the right size, but the TableView disappears after doing so:
Completely lost as to why this occurs. The label and button seem unaffected. I either need to make it so autolayout automatically adjusts the height of the UIView, or make it so that resizing the UIView does not cause the TableView to disappear.
In the View Debugger, the TableView is returning a height of 0 (while the rows are returning 130 as expected given that is what I return in my heightForRowAt function).
Thanks
Don't adjust the view frame if you are using Auto Layout.
Make a height constraint and adjust that to your calculated value.
-
Also it might be easier to manually calculate this height.
height = numberOfRows * heightPerRow
I'm trying to have a UITableView that lists all the different HomeKit devices a user has available.
Obviously there is no way to know how many devices they have, so I need to have the UITableView's height in the storyboard change.
I've tried this, which I call in the viewDidLoad() function:
func adjustHeightOfTableView() {
//getting the height of the tableview
var tableHeight = self.tableView.contentSize.height
//the height of the content inside the view
var maxHeight = self.tableView.superview?.frame.size.height
//if the height of the content is bigger then the height of the tableview
if (maxHeight! > tableHeight) {
tableHeight = maxHeight!
//set the tableview height to be the content height
}
//trying to reload the tableview height?
self.view.layoutIfNeeded()
self.tableView.reloadData()
}
I am trying to have some UI Elements under the tableview, and I want them to be a set space from the bottom of the tableview, but also have the tableview be the height that it needs to be, for whatever amount of cells there is.
But it's just not working.
If I'm doing anything wrong, or if anyone knows how to make this work, please let me know.
Thanks!
Note: For this approach you need to have static cell height or figure out a way to know before hand whats the total contentsize height
Assuming you are using constraints, create following constraints on your UITableView (apart from leading and trailing!)
Add a height constraint with a priority of 750 and a bottom spacing constraint of 0 to your super view that will be >= 0 and have a priority of 1000. Create outlet for this height constraint that you created in your UIViewController
Now,
func adjustHeightOfTableView() {
//set the height to be equal to the number of elements multiplied by the height of each cell.
//or use some logic that allows you to know what content size or space the cells will occupy!
tableViewHeightConstraint.constant = dataArray.count * rowHeight
view.layoutIfNeeded()
}
Now if your UITableView height is less than super view, no problems! But if it is greater than screen bounds, it will break the height constraint and become full screen and display the content normally as you expect a UITableView to!
Edit:
Even if you are using UIAutomaticRowDimensions what you can do is add constraints programmatically to your UITableView. i.e
Of course all your other views will still have a bottom constraint to your UITableView.
Create a UITableView in your storyboard with normal leading, trailing, top and bottom to the super view. Fetch the data. Get the contentSize for your UITableView and then remove the bottom constraint. Now add a height constraint that will be the minimum value of your UIScreen.main().bounds.size.height and contentSize.
you can use Automatic Dimensions if you are using autolayouts
in view didload:
let nib = UINib(nibName: "YOURCELLNIB", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "REUSEIDENTIFIER")
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 140
Remove the function
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath)
In your code, you have:
tableHeight = maxHeight!
//set the tableview height to be the content height
But this does not change the table height - it only changes some variable that previously was assigned the value of the old table content height. Nowhere in your code do you actually do anything to change the table height.
One way to change the table height directly is to assign it a completely new frame with values from the old frame, except for the frame's height, which you calculate however you like.
Try something like this (adding whatever other logic you need):
oldFrame = self.tableView.frame
newHeight = rowCount * rowHeight
self.tableView.frame = CGRectMake(oldFrame.origin.x, oldFrame.origin.y, oldFrame.size.width, newHeight)
There is a workaround which can make it seems like the height changes according to the number of the cells.
set tableview height to a proper value when init.
UITableView.init(frame: CGRect.init(x: 0, y: 70, width: self.view.frame.width, height: self.view.frame.height - 350))
set the tableview background color white transparent.
pulldownTableView?.backgroundColor = UIColor.white.withAlphaComponent(0)
set tableFooterView.
pulldownTableView?.tableFooterView = UIView(frame: CGRect.zero)
Below is the result, there are two table in the img. I set the transparent for the front tableview, left img set the backgroundColor to white, right white transparent.
----------------------vs----------------
I'm trying to put a uitableview within a uitableviewcell.The number of cells are dynamic, and the inner table view height should be the contentsize height. (Please refer to the images below) The first time the view loads it does not calculate the height of the cell correctly in that it only expands to the height of the label. After scrolling down and then back up so the cell reloads, it calculates the height correctly. Anyone have any ideas to fix this. I have included the cell's, the label's, and the inner tableview's constrains.
- (CGSize)systemLayoutSizeFittingSize:(CGSize)targetSize withHorizontalFittingPriority:(UILayoutPriority)horizontalFittingPriority verticalFittingPriority:(UILayoutPriority)verticalFittingPriority {
CGRect rect = self.answerOptionsTable.frame;
rect.size.height = MAXFLOAT;
self.answerOptionsTable.frame = rect;
[self.answerOptionsTable layoutIfNeeded];
CGSize returnedSize;
if ( self.answerOptionsTable.contentSize.height > self.lblQuestion.frame.size.height )
{
returnedSize = self.answerOptionsTable.contentSize;
}
else
{
returnedSize = self.lblQuestion.frame.size;
}
// add some padding
returnedSize.height += 20;
return returnedSize;
}
Cell Constraints
Table Constraints
Label Constraints
Initial draw
After reload of cell
Here is another example with smaller number of rows initial draw
Smaller number of rows after cell redraw
I am very new to iOS. Can anyone tell me how to fix this, to fill all my view with UITableView:
I am trying to do it with auto layout and constraints but I don't know why isn't working.
What you want to do is to have the cells at equal height so that all cells together fit exactly the height of the screen.
You cannot do that with auto layout. You have to tell the table view the height you'd like the rows to have like so:
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
let heightOfVisibleTableViewArea = view.bounds.height - topLayoutGuide.length - bottomLayoutGuide.length
let numberOfRows = tableView.numberOfRowsInSection(0)
tableView.rowHeight = heightOfVisibleTableViewArea / CGFloat(numberOfRows)
}
Note that this code assumes that you don't implement the method tableView(_:heightForRowAtIndexPath:).
To fill the whole view, with a table view, I use four constraints:
One. tableView centre = view centre.
Two. tableView width = view width.
Three. tableView vertical distance to top layout guide = 0
Four. tableView vertical distance to bottom layout guide = 0.
To fill everything with the same color, I set the backgroundColor of the tableView, then set the backgroundColor of the cells to [UIColor clearColor].
I have a view and table view design using Autolayout and Constraints. I have successfully design view using Autolayout.
But I have one more requirement in table view cell content. ** I want to increase LABEL height accordingly text (Depend on content of label text- Label 1). Please review attached screen shot. I have set CELL into the table view using Storyboard. Table view cell into I have taken 3 Labels.**
Label -2 : I have set constraint label-2, Leading edge constraint-5, Trailing edge constraint-5, Top edge constraint-10, Bottom constraint-0. Here I set height of Label-2 20. It fixed and I do not want to increase them.
Label -3 : I have set constraint label-3, Leading edge constraint-5, Trailing edge constraint-5, Top edge constraint-0, Bottom constraint-5. Here I set height of Label-3 20. It fixed and I do not want to increase them.
I want to increase height of Label 1 according to text.
**_Label -1 :_** I want to increase size of Label 1. I have set constraint label-1, Leading edge constraint-5, Trailing edge constraint-5, Top edge constraint-5, Bottom constraint-10. Here I set height of Label-1 35.
Right now, I have not set constraint of Label-1 height constraint. I have also tried set height constraint but it’s cannot take effect on height increases issues.
I have created method for Label-1. It was count label-1 size and increases it accordingly. But it was not return current height.
Here, I set table view cell size 95. And it will be increase dynamically using table view height delegate method.
_
Source Code :-_
UITableViewSource Method:
//Count Height of table view cell
public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath indexPath){
TableViewCellClass cell = null;
cell = (TableViewCellClass)tableView.DequeueReusableCell(cellIdentifier);
return cell.RequiredTableViewCellHeight(tableView.Bounds.Size.Width);
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath){
TableViewCellClass cell = (TableViewCellClass)tableView.DequeueReusableCell(cellIdentifier,indexPath);
//Add Data In Cell
cell.Updatecell (tableItems [indexPath.Row].Label1Data, tableItems [indexPath.Row].Label2Data, tableItems [indexPath.Row].Label3Data);
return cell;
}
TableView Cell Method:-
partial class TableViewCellClass : UITableViewCell{
public TableViewCellClass (IntPtr handle) : base (handle)
{
}
public void Updatecell (string lbl1Data, string lbl2Data, DateTime lbl3Data){
Label1.Text = lbl1Data; //I want to increases height of label1
Label2.Text = lbl2Data;
Label3.Text = lbl3Data.ToString();
//Here Below, fixed text and size for Label-2 and Label-3. It was fixed and never increase it's height
Label2.SizeToFit();
Label2.AdjustsFontSizeToFitWidth = true;
Label3.SizeToFit();
Label3.AdjustsFontSizeToFitWidth = true;
}
//RequiredTableViewCellHeight Method For Count Label Hight and Increase Cell According to it.
public float RequiredTableViewCellHeight(nfloat screenWidth){
Console.WriteLine("screenWidth : {0}",screenWidth); //Here we get the screen size of table view WIDTh
//Here make dynamic lable
Label1.Lines = 0;
Label1.AdjustsFontSizeToFitWidth = false;
UIFont cellFont = Label1.Font;
nfloat lbl1widthVal = screenWidth - 10; //Here we Minus 10 due to leading and trailing constraint. So Width not effected.
//Below Count the size of label height accordingly text and font size. Size not return actuall size. It's some time return always same.
CGSize lbl1Size = ((NSString) Label1.Text).StringSize(cellFont,constrainedToSize:new CGSize(lbl1widthVal,400.0f),lineBreakMode:UILineBreakMode.WordWrap);
Console.WriteLine("lbl1Size Total Size: {0}",lbl1Size);
int rowHeight = (int)lbl1Size.Height; //Get the Height of table cell
Console.WriteLine("rowHeight: {0}",rowHeight);
rowHeight += 60; //Add extra 60 due to label-2, label-3 size and spacing value in cell
Console.WriteLine("After Final Edit rowHeight value: {0}",rowHeight);
return (float)rowHeight;
}
}
Can i fetch issues due to autolayout or I do make mistake somewhere in code?
Please note that, I do not want to remove autolayout in project.
Please review that and let us know your suggestions. Thank in advance!
Self sizing views (tableviewcells) might be of use to you.
You set the constraints, then set tableView.estimatedRowHeight = 44.0 (for example)
Then set tableView.rowHeight = UITableViewAutomaticDimension
Here is a tutorial about this: http://www.appcoda.com/self-sizing-cells/