Reputation: 606
I am trying to display an image on a UICollectionViewCell:
Here is the Page Class:
struct Page {
let imageName: UIImageView
let headerText: String
let bodyText: String
}
Here is where I assign the image and text to each part of the view:
func one(){
let imageView = UIImageView(image: #imageLiteral(resourceName: "burger"))
pages = [
Page(imageName: imageView, headerText: "headerText", bodyText: "bodyText"),
Page(imageName: imageView, headerText: "headerText", bodyText: "bodyText"),
Page(imageName: imageView, headerText: "headerText", bodyText: "bodyText"),
Page(imageName: imageView, headerText: "headerText", bodyText: "bodyText"),
Page(imageName: imageView, headerText: "headerText", bodyText: "bodyText"),
Page(imageName: imageView, headerText: "headerText", bodyText: "bodyText")
]
}
This is how I set image constraints:
private let bearImageView: UIImageView = {
let imageView = UIImageView(image: #imageLiteral(resourceName: "burger"))
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
return imageView
}()
also
let topImageContainerView = UIView()
addSubview(topImageContainerView)
topImageContainerView.translatesAutoresizingMaskIntoConstraints = false
topImageContainerView.topAnchor.constraint(equalTo: topAnchor).isActive = true
topImageContainerView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
topImageContainerView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
topImageContainerView.addSubview(bearImageView)
bearImageView.centerXAnchor.constraint(equalTo: topImageContainerView.centerXAnchor).isActive = true
bearImageView.centerYAnchor.constraint(equalTo: topImageContainerView.centerYAnchor).isActive = true
bearImageView.heightAnchor.constraint(equalTo: topImageContainerView.heightAnchor, multiplier: 0.6).isActive = true
The problem is that when I run the code the text is displayed perfectly, but the image is no appearing at all.
I am totally lost with this and any help would be welcome!
Upvotes: 0
Views: 67
Reputation: 100541
You use a refrence type imageView inside a struct
let imageView = UIImageView(image: #imageLiteral(resourceName: "burger"))
it will be 1 item eventuallyb regardless of posts
count , despite you should have
let imageName: String
or
let image: UImage
Outlets are weak so when you assign
UIImageView
type it won't be retained even for that 1 single imageView object
Edit : set a height constraint for topImageContainerView
and a bottom to view same for the inner imageView
Upvotes: 1