Code Script πŸš€

Using Auto Layout in UITableView for dynamic cell layouts variable row heights

February 15, 2025

Using Auto Layout in UITableView for dynamic cell layouts  variable row heights

Creating dynamic and partaking person interfaces is important for immoderate palmy iOS app. Harnessing the powerfulness of Car Structure inside UITableView cells permits builders to trade versatile layouts that accommodate seamlessly to various contented sizes, finally enhancing the person education. This attack eliminates the limitations of fastened-tallness cells and opens ahead a planet of plan potentialities, from displaying multi-formation matter labels to embedding analyzable views inside all compartment. Fto’s delve into the intricacies of implementing Car Format successful UITableView to accomplish dynamic compartment layouts and adaptable line heights.

Knowing the Instauration: Car Structure and UITableView

Car Format is a almighty format scheme that defines relationships betwixt UI parts, enabling them to accommodate to antithetic surface sizes and orientations. Once mixed with UITableView, it offers the flexibility to make dynamic compartment layouts that set primarily based connected the contented inside all compartment. This eliminates the demand for guide tallness calculations, which tin beryllium tedious and mistake-inclined.

Earlier Car Format, builders frequently resorted to analyzable calculations to find compartment heights, particularly once dealing with adaptable contented similar dynamic matter labels oregon photographs. This attack was not lone clip-consuming however besides inclined to errors. Car Structure simplifies this procedure by permitting builders to specify constraints that govern the structure of components inside all compartment. The scheme robotically calculates the optimum tallness primarily based connected these constraints, guaranteeing that each contented is displayed accurately careless of its measurement.

Implementing Car Structure successful UITableView Cells

Implementing Car Structure successful your UITableViewCells includes respective cardinal steps. Archetypal, guarantee that all UI component inside the compartment has constraints that specify its assumption and measurement comparative to another components and the compartment’s contentView. These constraints dictate however the component volition resize and reposition itself once the contented modifications. 2nd, fit the tableView.rowHeight place to UITableView.automaticDimension. This tells the array position to dynamically cipher the tallness of all compartment based mostly connected its contented and the outlined Car Structure constraints. Eventually, supply an estimated line tallness utilizing tableView.estimatedRowHeight. This estimation helps the array position execute first structure calculations much effectively.

Selecting the correct constraints is indispensable for attaining the desired format. For case, once dealing with multi-formation labels, guarantee that the figure of strains is fit to zero and that apical, bottommost, starring, and trailing constraints are decently fit. This permits the description to grow vertically arsenic wanted. For representation views, specify facet ratio constraints and due spacing to neighboring components. Cautious information of these constraints ensures that the compartment format adapts appropriately to antithetic contented sizes.

Dealing with Analyzable Layouts with Stack Views

UIStackView simplifies the instauration of analyzable layouts inside UITableViewCells. Stack views negociate the agreement of their subviews, both vertically oregon horizontally, making it simpler to specify relationships betwixt parts. By embedding parts inside stack views, you tin make intricate layouts piece leveraging the powerfulness of Car Format. This simplifies the constraint explanation procedure and improves codification maintainability.

For illustration, you may usage a vertical stack position to put a rubric description, a multi-formation statement description, and an representation position inside a compartment. The stack position manages the spacing and alignment of these components, piece Car Structure ensures that the compartment’s tallness adjusts based mostly connected the contented of all component. This operation of stack views and Car Format permits for versatile and responsive compartment designs.

Optimizing Show with ContentView

A important facet of utilizing Car Structure with UITableView includes the contentView place of UITableViewCell. The contentView acts arsenic the instrumentality for each UI components inside the compartment. It’s indispensable to adhd each your views arsenic subviews of the contentView and specify constraints comparative to it. This ensures that Car Structure calculations are carried out accurately and that the compartment’s tallness is decided precisely.

Debar including constraints straight to the compartment itself. Alternatively, ever constrain your views inside the boundaries of the contentView. This pattern helps forestall sudden structure points and improves show by guaranteeing that Car Format operates effectively inside the meant range of the compartment’s contented country. Deliberation of the contentView arsenic the canvas for your compartment’s structure.

  1. Adhd subviews to the contentView.
  2. Fit constraints comparative to the contentView.
  3. Fit tableView.rowHeight to UITableView.automaticDimension.
  4. Supply an estimated line tallness.
  • Usage Car Format for dynamic contented.
  • Leverage UIStackView for analyzable layouts.

Debugging Car Format Points

Piece Car Format simplifies dynamic compartment layouts, debugging structure points tin generally beryllium difficult. Xcode gives instruments to aid place and resoluteness these points. The Position Debugger permits you to visualize the constraints utilized to your views, making it simpler to place conflicting oregon lacking constraints. Usage the console to place immoderate Car Structure warnings oregon errors that whitethorn bespeak issues with your constraints.

Communal points see ambiguous layouts wherever constraints don’t full specify the assumption and measurement of an component, oregon conflicting constraints that supply contradictory directions. The Position Debugger and console logs are invaluable instruments for pinpointing these points and making certain that your layouts behave arsenic anticipated. Knowing however to construe Car Format warnings and errors is important for businesslike debugging.

β€œCar Structure is a cornerstone of contemporary iOS improvement, permitting for dynamic and adaptive person interfaces. Mastering its intricacies is indispensable for creating genuinely responsive and partaking app experiences.” - Paul Hegarty, Stanford Body.

For case, ideate a societal media app displaying posts with various lengths of matter and pictures. Car Format permits all compartment to dynamically set its tallness to accommodate the contented, creating a seamless scrolling education. Larn much astir optimizing array position show.

  • Interface Builder simplifies constraint instauration.
  • Programmatic constraints message flexibility.

FAQ: What is the quality betwixt intrinsic contented dimension and express constraints? Intrinsic contented measurement is the earthy dimension of a position primarily based connected its contented (e.g., a description’s matter). Specific constraints override intrinsic contented measurement and dictate the position’s measurement and assumption based mostly connected outlined relationships with another views.

By embracing Car Format and its almighty options, you tin unlock the afloat possible of UITableView and present an distinctive person education. This attack not lone simplifies improvement however besides ensures that your app seems large connected immoderate instrumentality and adapts seamlessly to various contented. Research the linked assets to additional heighten your knowing of Car Format and UITableView champion practices: Pome’s UITableView Documentation, Car Structure Usher, and Ray Wenderlich Car Structure Tutorial.

Question & Answer :
However bash you usage Car Structure inside UITableViewCells successful a array position to fto all compartment’s contented and subviews find the line tallness (itself/robotically), piece sustaining creaseless scrolling show?

TL;DR: Don’t similar speechmaking? Leap consecutive to the example initiatives connected GitHub:

Conceptual Statement

The archetypal 2 steps beneath are relevant careless of which iOS variations you are processing for.

  1. Fit Ahead & Adhd Constraints

Successful your UITableViewCell subclass, adhd constraints truthful that the subviews of the compartment person their edges pinned to the edges of the compartment’s contentView (about importantly to the apical AND bottommost edges). Line: don’t pin subviews to the compartment itself; lone to the compartment’s contentView! Fto the intrinsic contented dimension of these subviews thrust the tallness of the array position compartment’s contented position by making certain the contented compression opposition and contented hugging constraints successful the vertical magnitude for all subview are not being overridden by greater-precedence constraints you person added. (Huh? Click on present.)

Retrieve, the thought is to person the compartment’s subviews related vertically to the compartment’s contented position truthful that they tin “exert force” and brand the contented position grow to acceptable them. Utilizing an illustration compartment with a fewer subviews, present is a ocular illustration of what any (not each!) of your constraints would demand to expression similar:

Example illustration of constraints on a table view cell.

You tin ideate that arsenic much matter is added to the multi-formation assemblage description successful the illustration compartment supra, it volition demand to turn vertically to acceptable the matter, which volition efficaciously unit the compartment to turn successful tallness. (Of class, you demand to acquire the constraints correct successful command for this to activity appropriately!)

Getting your constraints correct is decidedly the hardest and about crucial portion of getting dynamic compartment heights running with Car Structure. If you brand a error present, it may forestall every thing other from running – truthful return your clip! I urge mounting ahead your constraints successful codification due to the fact that you cognize precisely which constraints are being added wherever, and it’s a batch simpler to debug once issues spell incorrect. Including constraints successful codification tin beryllium conscionable arsenic casual arsenic and importantly much almighty than Interface Builder utilizing format anchors, oregon 1 of the improbable unfastened origin APIs disposable connected GitHub.

  • If you’re including constraints successful codification, you ought to bash this erstwhile from inside the updateConstraints technique of your UITableViewCell subclass. Line that updateConstraints whitethorn beryllium referred to as much than erstwhile, truthful to debar including the aforesaid constraints much than erstwhile, brand certain to wrapper your constraint-including codification inside updateConstraints successful a cheque for a boolean place specified arsenic didSetupConstraints (which you fit to Sure last you tally your constraint-including codification erstwhile). Connected the another manus, if you person codification that updates present constraints (specified arsenic adjusting the changeless place connected any constraints), spot this successful updateConstraints however extracurricular of the cheque for didSetupConstraints truthful it tin tally all clip the methodology is known as.
  1. Find Alone Array Position Compartment Reuse Identifiers

For all alone fit of constraints successful the compartment, usage a alone compartment reuse identifier. Successful another phrases, if your cells person much than 1 alone format, all alone format ought to have its ain reuse identifier. (A bully trace that you demand to usage a fresh reuse identifier is once your compartment variant has a antithetic figure of subviews, oregon the subviews are organized successful a chiseled manner.)

For illustration, if you have been displaying an electronic mail communication successful all compartment, you mightiness person four alone layouts: messages with conscionable a taxable, messages with a taxable and a assemblage, messages with a taxable and a photograph attachment, and messages with a taxable, assemblage, and photograph attachment. All format has wholly antithetic constraints required to accomplish it, truthful erstwhile the compartment is initialized and the constraints are added for 1 of these compartment sorts, the compartment ought to acquire a alone reuse identifier circumstantial to that compartment kind. This means once you dequeue a compartment for reuse, the constraints person already been added and are fit to spell for that compartment kind.

Line that owed to variations successful intrinsic contented dimension, cells with the aforesaid constraints (kind) whitethorn inactive person various heights! Don’t confuse basically antithetic layouts (antithetic constraints) with antithetic calculated position frames (solved from similar constraints) owed to antithetic sizes of contented.

  • Bash not adhd cells with wholly antithetic units of constraints to the aforesaid reuse excavation (i.e. usage the aforesaid reuse identifier) and past effort to distance the aged constraints and fit ahead fresh constraints from scratch last all dequeue. The inner Car Structure motor is not designed to grip ample standard modifications successful constraints, and you volition seat monolithic show points.

For iOS eight - Same-Sizing Cells

three. Change Line Tallness Estimation

To change same-sizing array position cells, you essential fit the array position’s rowHeight place to UITableViewAutomaticDimension. You essential besides delegate a worth to the estimatedRowHeight place. Arsenic shortly arsenic some of these properties are fit, the scheme makes use of Car Structure to cipher the line’s existent tallness

Pome: Running with Same-Sizing Array Position Cells

With iOS eight, Pome has internalized overmuch of the activity that antecedently had to beryllium applied by you anterior to iOS eight. Successful command to let the same-sizing compartment mechanics to activity, you essential archetypal fit the rowHeight place connected the array position to the changeless UITableView.automaticDimension. Past, you merely demand to change line tallness estimation by mounting the array position’s estimatedRowHeight place to a nonzero worth, for illustration:

same.tableView.rowHeight = UITableView.automaticDimension; same.tableView.estimatedRowHeight = forty four.zero; // fit to any your "mean" compartment tallness is 

What this does is supply the array position with a impermanent estimation/placeholder for the line heights of cells that are not but onscreen. Past, once these cells are astir to scroll connected surface, the existent line tallness volition beryllium calculated. To find the existent tallness for all line, the array position routinely asks all compartment what tallness its contentView wants to beryllium based mostly connected the recognized mounted width of the contented position (which is primarily based connected the array position’s width, minus immoderate further issues similar a conception scale oregon accent position) and the car structure constraints you person added to the compartment’s contented position and subviews. Erstwhile this existent compartment tallness has been decided, the aged estimated tallness for the line is up to date with the fresh existent tallness (and immoderate changes to the array position’s contentSize/contentOffset are made arsenic wanted for you).

Mostly talking, the estimation you supply doesn’t person to beryllium precise close – it is lone utilized to appropriately dimension the scroll indicator successful the array position, and the array position does a bully occupation of adjusting the scroll indicator for incorrect estimates arsenic you scroll cells onscreen. You ought to fit the estimatedRowHeight place connected the array position (successful viewDidLoad oregon akin) to a changeless worth that is the “mean” line tallness. Lone if your line heights person utmost variability (e.g. disagree by an command of magnitude) and you announcement the scroll indicator “leaping” arsenic you scroll ought to you fuss implementing tableView:estimatedHeightForRowAtIndexPath: to bash the minimal calculation required to instrument a much close estimation for all line.

For iOS 7 activity (implementing car compartment sizing your self)

three. Bash a Structure Walk & Acquire The Compartment Tallness

Archetypal, instantiate an offscreen case of a array position compartment, 1 case for all reuse identifier, that is utilized strictly for tallness calculations. (Offscreen which means the compartment mention is saved successful a place/ivar connected the position controller and ne\’er returned from tableView:cellForRowAtIndexPath: for the array position to really render onscreen.) Adjacent, the compartment essential beryllium configured with the direct contented (e.g. matter, photographs, and so forth) that it would clasp if it have been to beryllium displayed successful the array position.

Past, unit the compartment to instantly structure its subviews, and past usage the systemLayoutSizeFittingSize: technique connected the UITableViewCell’s contentView to discovery retired what the required tallness of the compartment is. Usage UILayoutFittingCompressedSize to acquire the smallest dimension required to acceptable each the contents of the compartment. The tallness tin past beryllium returned from the tableView:heightForRowAtIndexPath: delegate technique.

four. Usage Estimated Line Heights

If your array position has much than a mates twelve rows successful it, you volition discovery that doing the Car Structure constraint fixing tin rapidly lavatory behind the chief thread once archetypal loading the array position, arsenic tableView:heightForRowAtIndexPath: is known as connected all and all line upon archetypal burden (successful command to cipher the dimension of the scroll indicator).

Arsenic of iOS 7, you tin (and perfectly ought to) usage the estimatedRowHeight place connected the array position. What this does is supply the array position with a impermanent estimation/placeholder for the line heights of cells that are not but onscreen. Past, once these cells are astir to scroll connected surface, the existent line tallness volition beryllium calculated (by calling tableView:heightForRowAtIndexPath:), and the estimated tallness up to date with the existent 1.

Mostly talking, the estimation you supply doesn’t person to beryllium precise close – it is lone utilized to appropriately dimension the scroll indicator successful the array position, and the array position does a bully occupation of adjusting the scroll indicator for incorrect estimates arsenic you scroll cells onscreen. You ought to fit the estimatedRowHeight place connected the array position (successful viewDidLoad oregon akin) to a changeless worth that is the “mean” line tallness. Lone if your line heights person utmost variability (e.g. disagree by an command of magnitude) and you announcement the scroll indicator “leaping” arsenic you scroll ought to you fuss implementing tableView:estimatedHeightForRowAtIndexPath: to bash the minimal calculation required to instrument a much close estimation for all line.

5. (If Wanted) Adhd Line Tallness Caching

If you’ve achieved each the supra and are inactive uncovering that show is unacceptably dilatory once doing the constraint fixing successful tableView:heightForRowAtIndexPath:, you’ll unluckily demand to instrumentality any caching for compartment heights. (This is the attack urged by Pome’s engineers.) The broad thought is to fto the Autolayout motor lick the constraints the archetypal clip, past cache the calculated tallness for that compartment and usage the cached worth for each early requests for that compartment’s tallness. The device of class is to brand certain you broad the cached tallness for a compartment once thing occurs that may origin the compartment’s tallness to alteration – chiefly, this would beryllium once that compartment’s contented adjustments oregon once another crucial occasions happen (similar the person adjusting the Dynamic Kind matter measurement slider).

iOS 7 Generic Example Codification (with tons of juicy feedback)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // Find which reuse identifier ought to beryllium utilized for the compartment astatine this // scale way, relying connected the peculiar format required (you whitethorn person // conscionable 1, oregon whitethorn person galore). NSString *reuseIdentifier = ...; // Dequeue a compartment for the reuse identifier. // Line that this methodology volition init and instrument a fresh compartment if location isn't // 1 disposable successful the reuse excavation, truthful both manner last this formation of // codification you volition person a compartment with the accurate constraints fit to spell. UITableViewCell *compartment = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier]; // Configure the compartment with contented for the fixed indexPath, for illustration: // compartment.textLabel.matter = someTextForThisCell; // ... // Brand certain the constraints person been fit ahead for this compartment, since it // whitethorn person conscionable been created from scratch. Usage the pursuing traces, // assuming you are mounting ahead constraints from inside the compartment's // updateConstraints technique: [compartment setNeedsUpdateConstraints]; [compartment updateConstraintsIfNeeded]; // If you are utilizing multi-formation UILabels, don't bury that the // preferredMaxLayoutWidth wants to beryllium fit accurately. Bash it astatine this // component if you are NOT doing it inside the UITableViewCell subclass // -[layoutSubviews] methodology. For illustration: // compartment.multiLineLabel.preferredMaxLayoutWidth = CGRectGetWidth(tableView.bounds); instrument compartment; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { // Find which reuse identifier ought to beryllium utilized for the compartment astatine this // scale way. NSString *reuseIdentifier = ...; // Usage a dictionary of offscreen cells to acquire a compartment for the reuse // identifier, creating a compartment and storing it successful the dictionary if 1 // hasn't already been added for the reuse identifier. Informing: Don't // call the array position's dequeueReusableCellWithIdentifier: methodology present // due to the fact that this volition consequence successful a representation leak arsenic the compartment is created however // ne\'er returned from the tableView:cellForRowAtIndexPath: methodology! UITableViewCell *compartment = [same.offscreenCells objectForKey:reuseIdentifier]; if (!compartment) { compartment = [[YourTableViewCellClass alloc] init]; [same.offscreenCells setObject:compartment forKey:reuseIdentifier]; } // Configure the compartment with contented for the fixed indexPath, for illustration: // compartment.textLabel.matter = someTextForThisCell; // ... // Brand certain the constraints person been fit ahead for this compartment, since it // whitethorn person conscionable been created from scratch. Usage the pursuing traces, // assuming you are mounting ahead constraints from inside the compartment's // updateConstraints methodology: [compartment setNeedsUpdateConstraints]; [compartment updateConstraintsIfNeeded]; // Fit the width of the compartment to lucifer the width of the array position. This // is crucial truthful that we'll acquire the accurate compartment tallness for antithetic // array position widths if the compartment's tallness relies upon connected its width (owed to // multi-formation UILabels statement wrapping, and so on). We don't demand to bash this // supra successful -[tableView:cellForRowAtIndexPath] due to the fact that it occurs // robotically once the compartment is utilized successful the array position. Besides line, // the last width of the compartment whitethorn not beryllium the width of the array position successful // any instances, for illustration once a conception scale is displayed on // the correct broadside of the array position. You essential relationship for the diminished // compartment width. compartment.bounds = CGRectMake(zero.zero, zero.zero, CGRectGetWidth(tableView.bounds), CGRectGetHeight(compartment.bounds)); // Bash the format walk connected the compartment, which volition cipher the frames for // each the views based mostly connected the constraints. (Line that you essential fit the // preferredMaxLayoutWidth connected multiline UILabels wrong the // -[layoutSubviews] methodology of the UITableViewCell subclass, oregon bash it // manually astatine this component earlier the beneath 2 strains!) [compartment setNeedsLayout]; [compartment layoutIfNeeded]; // Acquire the existent tallness required for the compartment's contentView CGFloat tallness = [compartment.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].tallness; // Adhd an other component to the tallness to relationship for the compartment separator, // which is added betwixt the bottommost of the compartment's contentView and the // bottommost of the array position compartment. tallness += 1.zero; instrument tallness; } // Line: Fit the array position's estimatedRowHeight place alternatively of // implementing the beneath methodology, Until you person utmost variability successful // your line heights and you announcement the scroll indicator "leaping" // arsenic you scroll. - (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath { // Bash the minimal calculations required to beryllium capable to instrument an // estimated line tallness that's inside an command of magnitude of the // existent tallness. For illustration: if ([same isTallCellAtIndexPath:indexPath]) { instrument 350.zero; } other { instrument forty.zero; } } 

Example Initiatives

These initiatives are full running examples of array views with adaptable line heights owed to array position cells containing dynamic contented successful UILabels.

Xamarin (C#/.Nett)

If you’re utilizing Xamarin, cheque retired this example task option unneurotic by @KentBoogaart.