I have been trying to add custom background image to my app. I used the methods introduced here: How to fill background image of an UIView
These codes succeeded in both normal UIViewController and UITableViewController, but failed in UICollectionViewController. It is just all black.
As far as I understand, UITableViewController has the similar structure as UICollectionViewController. I compared the setting for these two controllers and they are all same (in the view section). How come the code works on one but not on the other one?
The best way to implement this is to implement through code inside your viewDidLoad for the CollectionView
let bgImage = UIImageView();
bgImage.image = UIImage(named: "bg4");
bgImage.contentMode = .ScaleToFill
self.collectionView?.backgroundView = bgImage
It is working on uicollectionview
self.collectionView?.backgroundColor = UIColor(patternImage: UIImage(named: "image.png")!)
A friend of mine has given me the solution.
The trick is to set collection view background to clear instead of default. I have set all views to default so I thought it should be the same in collection view.
But how come only in collection view the default background is black while in others the default is clear? It confuses me.
try this for set background image for UICollectionView Swift 4 or later
1. Add This extension in your code out of main class
extension UICollectionView {
func setEmptyMessage(_ message: String,_ img:UIImage) {
let image = UIImageView()
image.contentMode = .scaleAspectFit
image.image = img
let messageLabel = UILabel()
messageLabel.text = message
messageLabel.font = UIFont.boldSystemFont(ofSize: 20)
messageLabel.textColor = .gray
messageLabel.numberOfLines = 0
messageLabel.textAlignment = .center
messageLabel.sizeToFit()
let mainView = UIView()
mainView.addSubview(image)
mainView.addSubview(messageLabel)
//Auto Layout
image.translatesAutoresizingMaskIntoConstraints = false
image.centerXAnchor.constraint(equalTo: mainView.centerXAnchor).isActive = true
image.centerYAnchor.constraint(equalTo: mainView.centerYAnchor , constant: -40).isActive = true
messageLabel.translatesAutoresizingMaskIntoConstraints = false
messageLabel.topAnchor.constraint(equalTo: image.bottomAnchor, constant: 20).isActive = true
messageLabel.leadingAnchor.constraint(equalTo: mainView.leadingAnchor, constant: 10).isActive = true
messageLabel.trailingAnchor.constraint(equalTo: mainView.trailingAnchor, constant: 10).isActive = true
self.backgroundView = mainView
}
func restoreBackgroundView() {
self.backgroundView = nil
}
}
2. How to use
if Data.count == 0 {
self.collectionView.setEmptyMessage("set the message", UIImage(named: "imageName"))
} else {
self.collectionView.restoreBackgroundView()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With