How to programmatically increase UITableView cell's height in iPhone?
First of all take a bool
& int
variable.
BOOL isReadMoreButtonTouched = NO;
int indexOfReadMoreButton = -1;
Then Implement below with your code
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[[cell btnReadmore] setTag:[indexPath row]];
if(isReadMoreButtonTouched && [indexPath row]== indexOfReadMoreButton)
{
// design your read more label here
}
}
Now implement IBAction
-(IBAction) funReadmore:(id)sender
{
UIButton *readMoreButton = (UIButton *)sender;
indexOfReadMoreButton=[readMoreButton tag];
isReadMoreButtonTouched=YES;
[[self tableView] beginUpdates];
[[self tableView] reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForItem: indexOfReadMoreButton inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
[[self tableView] endUpdates];
}
Now Come to heightForRowAtIndexPath
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(isReadMoreButtonTouched && [indexPath row]== indexOfReadMoreButton) return 200.0f;
else return 100.0f;
}
Hope it'll work for you.
UITableView with variable cell height: Working in IB but not programmatically
The error is pretty trivial:
Instead of
self.addSubview(myCellLabel)
use
self.contentView.addSubview(myCellLabel)
Also, I would replace
// pin top
NSLayoutConstraint(...).active = true
// pin bottom
NSLayoutConstraint(...).active = true
// center horizontal
NSLayoutConstraint(...).active = true
with
let topConstraint = NSLayoutConstraint(...)
let bottomConstraint = NSLayoutConstraint(...)
let centerConstraint = NSLayoutConstraint(...)
self.contentView.addConstraints([topConstraint, bottomConstraint, centerConstraint])
which is more explicit (you have to specify the constraint owner) and thus safer.
The problem is that when calling active = true
on a constraint, the layout system has to decide to which view it should add the constraints. In your case, because the first common ancestor of contentView
and myCellLabel
is your UITableViewCell
, they were added to your UITableViewCell
, so they were not actually constraining the contentView
(constraints were between siblings not between superview-subview).
Your code actually triggered a console warning:
Warning once only: Detected a case where constraints ambiguously suggest a height of zero for a tableview cell's content view. We're considering the collapse unintentional and using standard height instead.
Which made me to look immediately at the way the constraints are created for your label.
Set Height Programmatically for a Single UITableViewCell?
There is a delegate function for the UITableViewCell height.
Here you specify the indexPath of that particular cell and return your height for it
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if(indexPath.section == yourSection && indexPath.row == yourRow) {
return 150.0;
}
// "Else"
return someDefaultHeight;
}
How to get height of UITableView when cells are dynamically sized?
I finally hacked out a solution:
tableView.contentSize.height
will not work for dynamic cells because they will only return the number of cells * estimatedRowHeight
.
Hence, to get the dynamic table view height, you look for all visible cells, and sum up their heights. Note that this only works for table views that are shorter than your screen.
However, before we do the above to look for visible cells, it is important to know that note we need to get the table view on the screen so that we can obtain visible cells. To do so, we can set a height constraint for the table view to some arbitrarily large number just so it appears on the screen:
Set height of table view constraint:
// Class variable heightOfTableViewConstraint set to 1000
heightOfTableViewConstraint = NSLayoutConstraint(item: self.tableView, attribute: .height, relatedBy: .equal, toItem: containerView, attribute: .height, multiplier: 0.0, constant: 1000)
containerView.addConstraint(heightOfTableViewConstraint)Call tableView.layoutIfNeeded(), and when completed, look for the visible cells, sum up their height, and edit the
heightOfTableViewConstraint
:UIView.animate(withDuration: 0, animations: {
self.tableView.layoutIfNeeded()
}) { (complete) in
var heightOfTableView: CGFloat = 0.0
// Get visible cells and sum up their heights
let cells = self.tableView.visibleCells
for cell in cells {
heightOfTableView += cell.frame.height
}
// Edit heightOfTableViewConstraint's constant to update height of table view
self.heightOfTableViewConstraint.constant = heightOfTableView
}
UITableViewCell dynamic height programmatically
For dynamic tableViewCell height use this.
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
CGSize labelHeight = [self heigtForCellwithString:yourLabel.text withFont:yourLabel.font];
return labelHeight.height; // the return height + your other view height
}
-(CGSize)heigtForCellwithString:(NSString *)stringValue withFont:(UIFont)font{
CGSize constraint = CGSizeMake(300,9999); // Replace 300 with your label width
NSDictionary *attributes = @{NSFontAttributeName: font};
CGRect rect = [stringValue boundingRectWithSize:constraint
options: (NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:attributes
context:nil];
return rect.size;
}
UITableview : Change cell height dynamically when clicked the custom button
Create an array to hold which cells should be expanded. When a button is pressed, add or remove an element to the array accordingly. Here is the code:
// Initialize an empty array of integers
var expandedCells = [Int]()
@IBAction func buttonPressed(_ sender: AnyObject) {
// If the array contains the button that was pressed, then remove that button from the array
if expandedCells.contains(sender.tag) {
expandedCells = expandedCells.filter({ $0 != sender.tag})
}
// Otherwise, add the button to the array
else {
expandedCells.append(sender.tag)
}
// Reload the tableView data anytime a button is pressed
tableView.reloadData()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell
// Set the tag on your button to be equal to indexPath.row
// This allows @IBAction func buttonPressed(_ sender: AnyObject) above to discern which row was tapped
cell.myButton.tag = indexPath.row
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
// Set the row height based on whether or not the Int associated with that row is contained in the expandedCells array
if expandedCells.contains(indexPath.row) {
return 102
} else {
return 57
}
}
How to auto resize tableview height + stackview
A few changes...
Right now, your 80-pt Height image view is limiting the contentStack
height to 80-points, so in your contentStack
setup, use either:
view.alignment = .top
// or
view.alignment = .center
Change your labelStack
setup to:
view.distribution = .fill // NOT .fillProportionally
make sure you set:
titleLabel.setContentCompressionResistancePriority(.required, for: .vertical)
descriptionLabel.setContentCompressionResistancePriority(.required, for: .vertical)
Edit
This is how it can look with long and short descriptions, and with / without an image. The labels have a cyan background and the image views have a yellow background so you can see the frames...
If that is leaving too much top and bottom "padding" you need to adjust your top and bottom constraint constants.
Related Topics
How to Save an Array to .Plist in the App's Mainbundle in Swift
Specifying One Dimension of Cells in Uicollectionview Using Auto Layout
Fixing Xcode 9 Issue: "iPhone Is Busy: Preparing Debugger Support for Iphone"
Add a Button on Right View of Uitextfield in Such Way That, Text Should Not Overlap the Button
Decode Base-64 Encoded Png in an Nsstring
How to Customize the Navigation Back Symbol and Navigation Back Text
Html5 Video Autoplay on Iphone
iPhone 6 and 6 Plus Responsive Breakpoints
Mobile Safari Position:Fixed Z-Index Glitch When Scrolling
CSS Gradient Not Working on iOS
Div Scrolling Freezes Sometimes If I Use -Webkit-Overflow-Scrolling
How Do We Create a Bigger Center Uitabbar Item
If No Table View Results, Display "No Results" on Screen
Firebase .Indexon Dynamic Keys