akim
akim

Reputation: 93

How to replicate UITableViewCell imageView in SwiftUI

In a normal storyboard/UIKit application, you can set the imageView of a cell in the cellForRowAt function as follows:

cell.imageView?.image = // some UIImage

When an imageView is set, the tableView's divider shortens to accommodate for the image, leaving no divider under the images itself, like in the default Settings app (Image)

However, in SwiftUI, this doesn't seem to be possible. You can, of course, replicate the content of the cells with a List and HStack, but the divider extends the whole bottom of the cell.

The workarounds I've tried look something along the lines of this:

UITableView.appearance().separatorStyle = .none

struct TableView: View {
  let arr = ["Alex", "Brian", "Charlie"]
  var body: some View {
    List(arr, id: \.self) { entry in
      HStack {
        Image(systemName: "person")
        VStack(alignment: .leading) {
          Text(String(entry))
          Divider()
        }
      }
    }
  }
}

but all of them don't align correctly like so.

Again, it's probably infeasible considering how SwiftUI works fundamentally and also a pretty trivial problem, but I thought it wouldn't hurt to ask. Fingers crossed for WWDC?

Upvotes: 2

Views: 403

Answers (1)

Dscyre Scotti
Dscyre Scotti

Reputation: 1427

Set HStack alignment to .firstTextBaseline.

HStack(alignment: .firstTextBaseline) {
    ...
}

Thanks. X_X

Upvotes: 1

Related Questions