如何使 UICollectionView 透明?

How do I make a UICollectionView transparent?

我几乎(真的?)尝试了所有方法来使水平 collection 视图透明并覆盖在地图视图上。

这是我的 collection 视图:

fileprivate let restaurantCollection : UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        let restaurant = UICollectionView(frame: .zero, collectionViewLayout: layout)
        restaurant.decelerationRate = .fast
        restaurant.backgroundView = nil
        restaurant.layer.backgroundColor = UIColor.clear.cgColor
        restaurant.backgroundColor = .clear
        restaurant.translatesAutoresizingMaskIntoConstraints = false
        restaurant.register(MapCell.self, forCellWithReuseIdentifier: "Cell")
        return restaurant
    }()

如你所见,背景清晰,图层清晰,背景视图为零。

而且单元格也是透明的:

func setupView() {
    contentView.backgroundColor = UIColor.clear.withAlphaComponent(0)

    contentView.addSubview(cellBackground)
    cellBackground.translatesAutoresizingMaskIntoConstraints = false
    cellBackground.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true
    cellBackground.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true
    cellBackground.trailingAnchor.constraint(equalTo: contentView.trailingAnchor).isActive = true
    cellBackground.bottomAnchor.constraint(equalTo: contentView.bottomAnchor).isActive = true
    }

我还向单元格 "backgroundView" 添加了一个视图,该视图的所有边都固定为常量 0。这也很清楚。

lazy var cellBackground : UIView = {
    let view = UIView(frame: CGRect(x: 10, y: 6, width: self.frame.width, height: 220))
    view.clipsToBounds = true
    view.backgroundColor = .clear
    view.layer.backgroundColor = UIColor.clear.cgColor
    return view
}()

经过所有努力,collection 视图仍然有白色背景

视图层次结构:这是仍然是白色的视图

您需要确保设置 backgroundColor 以清除

    self.collectionView.backgroundColor = UIColor.clear
    self.collectionView.backgroundView = UIView.init(frame: CGRect.zero)