当我不想要它时,UIButton是透明的

muf*_*ufc 7 uibutton ios uicollectionviewcell

我有一个按钮,我放在自定义UICollectionViewCell的顶角.出于某种原因,它显得半透明,以便当我不喜欢这种情况时,通过按钮显示单元格的边框.

在我的CustomCollectionviewCell中:

    lazy var favoriteButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(#imageLiteral(resourceName: "star_white").withRenderingMode(.alwaysOriginal), for: .normal)
        button.addTarget(self, action: #selector(favoriteTapped), for: .touchUpInside)
        button.isEnabled = true
        return button
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)

        backgroundColor = UIColor.mainWhite()
        layer.borderWidth = 1.0
        layer.borderColor = UIColor.lightGray.cgColor

        setupCellLayout()
    }


    fileprivate func setupCellLayout() {
        addSubview(favoriteButton)
        favoriteButton.translatesAutoresizingMaskIntoConstraints = false
        favoriteButton.heightAnchor.constraint(equalToConstant: 32).isActive = true
        favoriteButton.widthAnchor.constraint(equalToConstant: 32).isActive = true
        favoriteButton.centerXAnchor.constraint(equalTo: rightAnchor, constant: -12).isActive = true
        favoriteButton.centerYAnchor.constraint(equalTo: topAnchor).isActive = true
        bringSubview(toFront: favoriteButton)
    }
Run Code Online (Sandbox Code Playgroud)

这导致以下结果:

在此输入图像描述在此输入图像描述

这些图像都不是半透明的.他们有扎实的背景,所以我很困惑为什么他们在应用程序中显示为半透明.我原本以为他们可能被放在单元格后面,所以我bringSubview(toFront: favoriteButton)在setupCellLayout()中添加了这个调用,但是没有修复它.

我也认为使用.withRenderingMode(.alwaysOriginal)应该做的伎俩,但没有运气.

关于为什么会发生这种情况的任何想法?

Swa*_*uke 3

UIView是视图subviews主视图中的图层,并且显然没有办法将它们置于图层之上CALayer,因为这就像将它们带出视图一样。

您可以添加带边框的背景子视图,并在其前面添加所有其他视图。

或者,您可以插入背景子图层,并将边框应用到该图层。但是,请注意不要这样做addSublayer,因为它将被添加到子视图之上,而是将其插入到索引 0 处,这样它就在后面

    let backgroundLayer  = CALayer()
    backgroundLayer.frame  = layer.bounds
    backgroundLayer.borderColor = UIColor.lightGray.cgColor
    backgroundLayer.borderWidth = 1.0
    layer.insertSublayer(backgroundLayer, at: 0)
Run Code Online (Sandbox Code Playgroud)

另一个需要注意的重要点是确保插入层代码不会被重复调用。