قالب وردپرس درنا توس
Home / IOS Development / Self-adhesive table display cells | raywenderlich.com

Self-adhesive table display cells | raywenderlich.com



Update Note : Kevin Colligan updated this guide for Xcode 10, iOS 12, and Swift 4.2. Joshua Greene wrote the original.

If you have ever created custom table view cells before, there are good opportunities for spending a lot of time on the size of table display cells in code. You may even be able to calculate manually, the height of each label, image view, text box – and anything else in the cell.

Frankly, this approach is encouraging and incorrect. In this self-limiting table, the cells show the tutorial, you learn how to create and size table view cells dynamically to match the content. You can think: "It's going to take a lot of work!" No! :]

This tutorial assumes that you have a basic knowledge of Auto Layout and UITableView .

Getting Started

Today's iOS 6, Apple introduced a beautiful new technology: Auto Layout. Developers looked forward to it; parties began in the streets; bands wrote songs to celebrate their greatness …

OK, so it could be a stretch, but that was a big deal.

While the inspired hope for developers, Auto Layout was still cumbersome. Automatic setup management was manually, and still a good example of the versatility of iOS development. The Interface Builder was basically quite ineffective when setting up limitations.

Flash until now. With all the improvements to Interface Builder, it's easy to use Auto Layout to create self-size table display cells!

A few in-and-outs aside, all you have to do is:

  1. Use Auto Layout for the UI elements inside the table view.
  2. Set the table display rowHeight to UITableViewAutomaticDimension .
  3. Set EstimatedRowHeight or implement the Highest Estimate delegate method.

But you do not want to dive in theory right now, do you? You are ready to get down to the coding. Then get to the business with the project.

Training App Overview

Imagine you have a movie client client who wants an app to showcase a number of favorite movie directors and some of their most prominent work. Not just any board members, really just their favorite authors .

"Authors?" You ask, "It sounds French."

Oui, that is. The author's theory of film production originated in France in the 1

940s, and it basically means that the director is the creative force behind a movie. Not all directors are an author – just those who stamp each film with their individual styles. Imagine Tarantino or Scorsese. And not everyone agrees with this theory – do not get your scriptwriter started. But the client is always right so you're ready to start rolling.

There is one problem: "We started creating the app, but we stumbled on how to display the contents of a table view," your client admits. "Our table display cells must resize (gulp!) Dynamic! Can you make it work?"

You suddenly feel the urge to give a spiffy beret and start shouting on orders!

 Author

But you do not need gimmicks to be the client's iOS author – your programming skills will be sufficient!

First, download the client's code using the Download Materials button at the top or bottom of this tutorial. Expand the zip file and open the Author-initiated project. (Spoiler Notice: You can also open the Final Author Project to see how this app will look when you're done.)

In The Author Launcher Project opens Main .storyboard in the group Views under Author's project. You see three scenes:

 Main.storyboard

From left to right are they:

  • A top navigation navigation check.
  • AuthorListViewController displays a list of authors.
  • AuthorDetailViewController displays authors movies and information about each movie.

Construction and running. You see AuthorListViewController which lists a list of authors. Select the first author, Wes Anderson. The app will screen to AuthorDetailViewController to display a list of the selected author movies:

 View Controllers

Not only is the app missing images of each author and every movie that information you try to show is also cut off! Each piece of information and image will have a different size, so you can not only increase the cell height of the table and call it a wrap. Your cell heights must be dynamic based on the content of each cell.

You begin to implement dynamic cell heights in AuthorListViewController .

Creating Adaptive Table View Cells [19659006] To get dynamic cell heights that work properly, create a custom table display cell and set it up with the appropriate auto-set limitations.

In the project navigator, select the Views group and press Command-N to create a new file in this group. Create a new Cocoa Touch Class called AuthorTableViewCell and make it a subclass of UITableViewCell . Make sure that also create an XIB file is not marked and that the language is set to Swift .

 AuthorTableViewCell

open AuthorTableViewCell.swift . Then delete the two automatically generated methods and add the following property:

  @IBOutlet weak was bioLabel: UILabel!

Next, open Main.storyboard and select the cell in the table view of the Authors scene. I Identity Inspector Change Class to AuthorTableViewCell :

 AuthorTableViewCell

Drag and Drop a New UILBabel on the cell, and put the text of Bio . Enter the Lines for the new label (the number of lines the label may have most) to 0 in Attributespector . It should look like this:

 AuthorTableViewCell Identity Inspector

Specifying the number of lines is very important for dynamic size cells. A label with the number of lines set to 0 will grow based on how much text it shows. A label with the number of lines set to another number will shorten the text when it is not available.

Connect bioLabel the expiration of AuthorTableViewCell to the label on the cell. One quick way to do this is to right-click Cell in Document Overview and click-drag from the empty circle to the right of bioLabel under Outlets The popup menu of the label you wrote:

 Connect the BioLabel Outlet

The trick to get Auto Layout on a ] UITableViewCell is to make sure you have the limits to pin each subpoint on all sides – that is, each teaching should have leading, top, back and bottom constraints. Then, the built-in height of the teaching is used to dictate the height of each cell. You will do this now.

Note : If you are not familiar with Auto Layout, or you want an update to understand how to configure automatic setup, take a look at this tutorial. [19659049] Select the biomark and press the Pin button at the bottom of the storyboard. In this menu, select the four dotted lines towards the top of the menu. Then change leading and subsequent values ​​to 8 and click Add Restrictions . It looks like this:

 Add Limitations

This ensures that no matter how big or small the cell may be, the biomark is always:

  • 0 points from the top and bottom margins.
  • 8 points from leading and rear margins.
Review : Does this meet the previous automatic setup criteria?

  1. Does each teaching have limitations that point to all its sides? Yes
  2. Are there limitations that go from top to bottom of contentView? Yes

The bio label is linked to top and bottom margins with 0 points, so Auto Layout can now determine the height of the cell!

Awesome, your AuthorTableViewCell is set up! If you are building and running the app now, you will see it …

 One for the blooper wheel

… who is not right! Cut!

There is some code you must write before the cells can become dynamic.

Configure Table View

First, you must configure the table view to use the correct custom cell.

Open AuthorListViewController.swift (in the group ViewControllers ) and replace tableView (_: cellForRowAt :) with the following:

  func tableView
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath
) -> UITableViewCell {
la cells = tableView.dequeueReusableCell (
withIdentifier: "Cell",
for: indexPath) as! AuteurTableViewCell
la author = authors [indexPath.row]
cell.bioLabel.text = author.bio
cell.bioLabel.textColor = UIColor (red: 0.75, green: 0.75, blue: 0.75, alpha: 1.0)
return cell
}

The code above is quite simple: You cover a cell, enter the information with a text color and return the cell.

I AuthorListViewController.swift add these two code lines at the bottom of viewDidLoad () :

  tableView.rowHeight = UITableView.automaticDimension
tableview.estimatedRowHeight = 600

When setting the row height as UITableViewAutomaticDimension the table view is told to use the limitations for auto setup and the contents of the cells to determine each cell height.

To view the table view To do this you must also give a estimatedRowHeight . In this case, 600 is just an arbitrary value that works well in this case. For your own projects, you should choose a value that better matches the type of data you want to display.

Build and run and you should now see all the authors bio.

 AuthorListViewController

It looks better! But do you know what would make this app even more dramatic? A moody dark background.

Open Main.storyboard select the cell in the table view of the Author scene. The Color drop-down menu can be found in Attribute Inspector

 Background Color

Click Background and select Custom . In the window that appears, select the RGB Sliders tab and the Hex Color # box enter 161616 – this will give you a nice blackish background black is not cool enough for authors:]).

 Blackish

Press Return; Build and run your app. It should look like this:

 AuthorListViewController

Such a drama!

Adding Images

It's nice that you can now read the entire movie of each artist, but there are still more data to display. Each artist has a photo and a name. This app uses an external API to retrieve the information, so it's also a source tag. By using these add-ons, the app will look much better.

You must add a photo view to AuthorTableViewCell and another label for the author's name. You should also add a source tag to credit the image correctly. Open AuthorTableViewCell.swift and add the following properties:

  @IBOutlet weak were nameLabel: UILabel!
@IBOutlet weak was source: UILabel!
@IBOutlet weak was auteurImageView: UIImageView!
 Note: The image display name is  auteurImageView  instead of  imageView  because there is already a  imageView  property at  UITableViewCell  UITableViewCell ]. 

Adjust the bioblad now. It's hard to look at Main.storyboard with the dark cell background. Open Main.storyboard Select the bio label and choose a lighter color for the text.

 List your label

Note : It does not matter what you put bioLabel the color of the Main.storyboard because this code from AuthorListViewController.swift will override it when driving:
cell.bioLabel.textColor = UIColor (red: 0.75, green: 0.75,
blue: 0.75, alpha: 1.0)

Now remove the restrictions from the bio label so you can add more elements to the cell and change things around. In Document Overview you can find Limitations under the Bio Label. Select each of the four constraints (hold Shift key to select them all) and press Delete . Ignore any auto-setup alerts for now.

 Deleting Bio Label Limitations

Before adding more items, you need some elbow room. Select Cell from Document Overview . Thereafter, Row Height in changes the size inspector to 450 .

 Increase cellade height

Now, fill this space:

  • Drag an ImageView into the cell.
  • Draw a Label into the cell. Then, put the text to Name and the color of white.
  • Drag another Label into the cell. Then you put the text to Source its Font to System 13.0 and the color of white.

Move the items in the following order, from top to bottom (you want to add limitations soon):

  1. ImageView
  2. Name
  3. Bio
  4. Source

Then connect the outputs to the new image view and labels , using the same technique you used for the bio label:

 Connect the remaining outlets

Now it's time to set up more limitations. With the Pin menu to add these vertical constraints, you begin using the source tag label:

  • Pin bottom edge to source on to to ]] 16 points from the monitoring. top of the source label of 8 points from the bottom of the bio label.
  • The Top label from the bottom of the label.
  • Pin on the top edge of the nameplate 8 points from the bottom of the image view.
  • Clip on top edge of image view 0 points from the top of the content view.

Now add horizontal constraints. Use the Pin menu first to: Pin Forefront of the Name Mark to 8 Points from the Surveillance.

  • [Monitor].
     Shift-Click  labeled  name  label,  bio  label and  source  and select  Like width  from ]  menu. [19659000] Set  image display  to have a  height  and  width  of  300  points. ] Then use the Adjust menu to center all items: 

    • Shift-click image view, label, bio label and source label, and select Horizontal in container from Adjust Menu ].

    Finally (well, almost), you must put hugging priorities for the label and the bio label. Select NameLabel in Size Inspector and scroll down until you see Content Compression Priority . Horizontal and Vertical will both be set to 251 by default. Change the name tag's Vertical priority to 253 .

     Content Compression Priority

    Now select the biomark and view its Vertical priority to 252 and you're done with the storyboard for now.

    Note : Wait, what's the hug? Is this a romantic picture?

    Not exactly. Setting a higher priority on content framing means that the view will resist growing larger than its internal size. You told the storyboard to make your cell 450 points high, which is greater than the inherent size of your views. By setting a priority for vertical content, Xcode tells which view to expand if it needs to fill in the room.

    Open AuthorListViewController.swift and add the following two code lines to tableView (_: cellForRowAt :) after you insert bioLabel s text: 19659038] cell.auteurImageView.image = UIImage (Calling: auteur.image) cell.nameLabel.text = author.name cell.source.text = auteur.source

    Then add these lines after you enter textColor :

      cell.nameLabel.textColor = .white
    cell.bioLabel.textColor = UIColor (red: 0.75, green: 0.75, blue: 0.75, alpha: 1.0)
    cell.source.textColor = UIColor (red: 0.74, green: 0.74, blue: 0.74, alpha: 1.0)
    cell.source.font = UIFont.italicSystemFont (ofSize: cell.source.font.pointSize)
    cell.nameLabel.textAlignment = .center
    cell.selectionStyle = .none
    

    Build and run your app.

     Looks great!

    Looks good. But the authors are not square, so let's tweak tableView (_: cellForRowAt :) to add the following code just before return cell :

      cell.auteurImageView.layer.cornerRadius = cell.auteurImageView.frame.size.width / 2
    

    Then return to Main.storyboard and select the image view. Then select the Clip to Bounds option at Attributespector :

     Clip to Bounds

    Build and run your app again to see your author photos in a circular frame that fits the MGM lion:

     Circles are better

    You are about to complete the limitations of Author ListViewController but eagle-eyed readers may have noticed to Xcode cast a warning.

     You have problems

    If you click the warning, you will get more information. It turns out that the setup works fine in English, but you may be having trouble locating your app to use a language reading from right to left.

     Right to the left

    Xcode offers to resolve the issue. But you can do it yourself by adjusting one of the label's label restrictions. Return to Main.storyboard and select the name tag. In Size Inspector you can find Trailing Space restriction and click Edit .

     Trailing space

    Change operator from

     Greater or Equal

    And the Xcode warning is gone!

    Create Dynamic Height

    If you remember from the beginning, select an author presents a viewer that shows selected authors movies. The cells in this table view must also have dynamic height.

    The first step, as before, is to create another subclass of UITableViewCell .

    In the project navigator, select Views group and press Command-N to create a new file in this group. Create a new Cocoa Touch Class called FilmTableViewCell and make it a subclass of UITableViewCell .

    Open FilmTableViewCell.swift and similarly, delete the two automatically generated methods in FilmTableViewCell and then add these properties:

      @IBOutlet weak where movieImageView: UIImageView!
    @IBOutlet weak was filmTitleLabel: UILabel!
    @IBOutlet weak was moreInfoTextView: UITextView!
    

    Open Main.storyboard and select the cell in the table view in the scene Author Detail View Controller . Set custom class of the cell to FilmTableViewCell and change the row height of 300 to give you plenty of room to work with.

    Now, draw a image display a label and a text display . Add them as shown below (text view is at the very bottom):

     Author's Detail Review Controls

    Change the text in the text view to Click for details> and the label for Name Name ]. Change the mode of image display to Aspect Fit . Select the text view, in Attitude Inspector . Change the customization to Centered Set the text color to Red and Deactivate scrolling:

     No scroll

    Deactivation of scrolling is of equivalent importance to set a label to 0 lines. With scrolling disabled, the text view knows how to grow its size to fit all content, since the user can not scroll through the text.

    A little further down past where you disabled scrolling, remove the check from User Interaction enabled . This will allow touches to pass through the text view and trigger a selection of the cell itself. Then, set the background color to Clear Color .

    More tweaks " width="377" height="320" class="aligncenter size-medium wp-image-205456 bordered" srcset="https://koenig-media.raywenderlich.com/uploads/2018/10/rw-self-sizing-28-377x320.png 377w, https://koenig-media.raywenderlich.com/uploads/2018/10/rw-self-sizing-28.png 542w" sizes="(max-width: 377px) 100vw, 377px"/>

    Now select the cell in the Author Detail View Controller scene and set the background of Hex Color # 161616 just the way you did on stage Author . Select the nametag and set the text color to white so you can view it on Main.storyboard .

    Connect the three elements with the corresponding sockets, as you did with the first cell. [19659002] Now you add limitations. Begin with the text view and move up:

    • Point the bottom edge of text view 0 points from the bottom margin into the content view.
    • Pointing by of text view 8 points from the front and back margins of the content view.
    • Pin on the top edge of text view 8 points from the bottom of the label.
    • Point top of label 8 points from bottom of image view
    • Center name mark by selecting Horizontal in container Horizontal in container ] in Adjust the menu. Select both name and image display (use Shift-click ) and select Like width from Pin Pin Pin ] menu.
    • Pin 9003] top edge of image display 0 points from the top margin to the content view.
    • Pin the Leading and Trays of Image View 8 Points from the Front and Back Margins of the Content View

    You have finished the storyboard for now.

    Open AuthorDetailViewController.swift and replace tableView (_: cellForRowAt :) that you had to do with the previous display control. ] with the following:

      func tableView (_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
    -> UITableViewCell {
    la cells = tableView
    .dequeueReusableCell (withIdentifier: "Cell", for: indexPath) as! Film Tableview Cell
    la film = selectedAuteur.films [indexPath.row]
    cell.filmTitleLabel.text = film.title
    cell.filmImageView.image = UIImage (named: movie poster)
    cell.filmTitleLabel.textColor = .white
    cell.filmTitleLabel.textAlignment = .center
    cell.moreInfoTextView.textColor = .red
    cell.selectionStyle = .none
    
    return cell
    }
    

    This should look very familiar now. You dequeuing and casting your cell get a reference of the model struct you should display and then configure your cell before returning it.

    Now, in viewDidLoad () of the same class, add the following code to the end of the method:

      tableView.rowHeight = UITableView.automaticDimension
    tableview.estimatedRowHeight = 300
    

    Build and run your app. Click on one of the authors to watch their movies.

     Author Detail View Controller

    Not bad, but take it to the next level by adding expanding cells to reveal more info about each work. Your client will love this!

    Expanding Cells

    Since cell heights are driven by Auto Layout constraints and the content of each interface element, expanding the cell should be as simple as adding more text to the text view when the user loses that cell.

    Open AuthorDetailViewController.swift and add the following extension:

      extension AuthorDetailViewController: UITableViewDelegate {
    func tableView (_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    // 1
    guard la cells = tableView.cellForRow (ved: indexPath) as? FilmTableViewCell Other {
    return
    }
    
    was film = selectedAuteur.films [indexPath.row]
    
    // 2
    film.isExpanded =! film.isExpanded
    selectedAuteur.films [indexPath.row] = movie
    
    // 3
    cell.moreInfoTextView.text = film.isExpanded? film.plot: moreInfoText
    cell.moreInfoTextView.textAlignment = film.isExpanded? .left: .center
    cell.moreInfoTextView.textColor = film.isExpanded?
    UIColor (red: 0.75, green: 0.75, blue: 0.75, alpha: 1.0):
    .Red
    
    // 4
    tableView.beginUpdates ()
    tableview.endupdates ()
    
    // 5
    tableView.scrollToRow (on: indexPath, on: .top, animated: true)
    }
    }
    

    Here's what's happening:

    1. You ask tableView for a reference of the cell at the selected indexPath and then to get the corresponding Movie object.
    2. You replace isExpanded the state of Film the object and put it back into the array, which is necessary since structures are value types.
    3. Then change the Text View of the cell, depending on whether the work is expanded. If so, enter the text view to display the movie's info property. You also change the text alignment to .left and the color of light gray. If it is not expanded, put the text back to "Press for details>", the adjustment back to .center and the color back to red.
    4. Table view must update cell heights now. Calling startUpdates () and endUpdates () will force the table view to update the heights in an animated way.
    5. Finally, you tell the table view to scroll the selected row to the top of the table view in an animated fashion.

    Now in tableView (_: cellForRowAt :) add the following three lines at the end before returning the cell:

      cell. moreInfoTextView.text = film.isExpanded? film.plot: moreInfoText
    cell.moreInfoTextView.textAlignment = film.isExpanded? .left: .center
    cell.moreInfoTextView.textColor = film.isExpanded?
    UIColor (red: 0.75, green: 0.75, blue: 0.75, alpha: 1.0):
    .Red
    

    This code will cause a cell that is used to remember if it was previously in expanded mode.

    Build and run the app. When you tap a movie cell, you'll see that it expands to accommodate the entire text. But the picture animates a little bit strange.

    It will not be hard to fix! Open Main.storyboard Select the image view in FilmTableViewCell and open the Size Inspector . Change Content Hugging Priority and Content Compression Resistance Priority to the values ​​in the image below:

     Hugs

    Enter Vertical Content Hugging Priority Vertical Content Hugging Priority ] to 252 will help the image view to squeeze the content and not extend during the animation. Setting Vertical Compression Resistance Priority to 1000 prevents the image from being compressed if other interface elements grow around it.

    Build and run the app. Select an author and tap the movies. You should see some very steady cell expansion, revealing information about each movie.

    Implementation Dynamic Type

    You have shown your progress to the client and they love it! But they have a final request. De vil at appen skal støtte funksjonen Større teksttilgjengelighet. Appen må tilpasse seg kundens foretrukne lesestørrelse.

    Introdusert i iOS 7, gjør Dynamic Type denne oppgaven enkel. Det gir utviklere muligheten til å spesifisere forskjellige tekststiler for ulike tekstblokker (som overskrift eller kropp) og få den teksten til å justere automatisk når brukeren endrer den foretrukne størrelsen i enhetens innstillinger.

    Gå tilbake til Main.storyboard og Auteurs scenen. Select the name label and, in the Attributes inspectorcomplete the following steps:

    1. Click the “T” icon in Font.
    2. Select Headline from under Text Styles.
    3. Check the Automatically Adjusts Font box
    4. Set the Lines to 0.

    Dynamic Text

    Do the same with the bio label, but choose Body under Text Styles instead of Headline.

    On the Auteur Detail View Controller scene, take the same steps with the name label, setting its Text Style to Headline. Set the text style of the Text View to Body (there is no Lines adjustment since this isn’t a label).

    That’s all you need to do to make the app more accessible. Build and run your app.

    Click the Home button on your simulator and open the Settings app, then click General ▸ Accessibility ▸ Larger Text and drag the slider to the right to increase the text size to a large setting:

    Larger Accessibility Sizes

    Then, go back to the Auteurs app’ your text should now appear larger. Thanks to your work on getting the dynamically sized cells, the table view still looks great:

    Larger Type

    Where to Go From Here?

    Congratulations on completing this tutorial on self-sizing table view cells!

    You can download the completed version of the project using the Download Materials button at the top or bottom of this tutorial.

    Table views are perhaps the most fundamental of structured data views in iOS. As your apps get more complex, you’re likely to use all sorts of custom table view cell layouts. You can delve deeply into Auto Layout in the Mastering Auto Layout video course.

    If you have any comments or questions, please respond below!


  • Source link