Passing UIView to Reusable cell using UIContentConfiguration and UIContentView

132 views Asked by At

I am trying to add a UIView programatically to a UIContentView, using the UIContentConfiguration. In the configure method I add the custom view as a Subview. I also keep a weak reference to it so I can remove it if the configuration says so. But for some reason my added views are not consistently present ( sometimes they show sometimes they don't ). Has anyone encountered this before ? (I know about supplementary items but it would be nice for me to be able to add them this way).

I tried adding as subview and removing the view in the configure method but they are not consistent.

struct ContentConfiguration: UIContentConfiguration {
    weak var myView: UIView?
    func makeContentView() -> UIView & UIContentView {
        MyContentView(self)
    }
}
class MyContentView: UIView, UIContentView {
    private var containerView: UIView = {
        var view = UIView()
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    init(_ configuration: ContentConfiguration {
        self.configuration = configuration
        super.init(frame:.zero)
        setupViews() // programatically set constraints for the container view
        configure(with: configuration)
    }
    configure(with configuration: UIContentConfiguration) {
        guard let configuration = configuration as? ContentConfiguration else {return}
        if let myView = configuration.myView {
            containerView.addSubview(myView)
        } else {
            containerView.subviews.foreach{$0.removeFromSuperview()}        
        }
    }
}
0

There are 0 answers