1

I have a UICollectionView and I'm trying to design my UICollectionViewCell's using SwiftUI. I've seen two examples, one and two that have done this in the following manner in their UICollectionViewCell:

let controller = UIHostingController(rootView: SomeSwiftUIView)
let view = controller.view!
view.translatesAutoresizingMaskIntoConstraints = false
addSubview(view)
NSLayoutConstraint.activate([
    view.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
    view.topAnchor.constraint(equalTo: contentView.topAnchor),
    view.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
    view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
])

This works fine visually, but a problem I'm having is I do not have user interaction with the SwiftUI view. For example, if I have a Button in the SwiftUI view, the action is not performed when you tap the button. If a List is in the SwiftUI view, you cannot scroll this view. (I'm not trying to put a List in it, this is just an example)

Any recommendations on where to go from here? Thanks!

2 Answers 2

1

I solved this by constraining the view to the cell rather than the contentView, and it is working fine now.

NSLayoutConstraint.activate([
    view.leadingAnchor.constraint(equalTo: leadingAnchor),
    view.topAnchor.constraint(equalTo: topAnchor),
    view.trailingAnchor.constraint(equalTo: trailingAnchor),
    view.bottomAnchor.constraint(equalTo: bottomAnchor)
])

As I suspected, this was a layering issue.

Sign up to request clarification or add additional context in comments.

Comments

0

You are adding the view to the cell directly and setting the constraints on the contentView.

When you add the view to the content view it will work as expected, so looking at your code if we only have to change the 4th line to contentView.addSubview(view) like so it would become:

let controller = UIHostingController(rootView: SomeSwiftUIView)
let view = controller.view!
view.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(view)

NSLayoutConstraint.activate([
    view.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
    view.topAnchor.constraint(equalTo: contentView.topAnchor),
    view.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
    view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
])

Apple also suggests to add the content of a cell into the content view and not directly into the view of the cell. See docs

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.