ios - UIButton 在我不希望它是透明的时候是透明的

标签 ios uibutton 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)
    }

结果如下:

enter image description here enter image description here

这些图像都不是半透明的。他们有坚实的背景,所以我很困惑为什么他们在应用程序中显示为半透明。我最初认为也许它们被放置在单元格后面,所以我在 setupCellLayout() 中添加了对 bringSubview(toFront: favoriteButton) 的调用,但这并没有解决它。

我还认为使用 .withRenderingMode(.alwaysOriginal) 应该可以解决问题,但运气不好。

关于为什么会发生这种情况有什么想法吗?

最佳答案

UIViewsubviews 是 View 的主要 CALayer 中的层,而且,显然有 no way to bring them above the layer ,因为这就像将它们带出视野。

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

或者,您可以插入一个背景子层,并为该层应用边框。但是,请注意不要addSublayer,因为它会被添加到 subview 之上,而是将它插入到索引 0 处,所以它在后面

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

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

关于ios - UIButton 在我不希望它是透明的时候是透明的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52405044/

相关文章:

objective-c - 无法使用 removeFromSuperView 删除 MPMoviePlayerController

iOS7 与 Xcode 6 的兼容性

ios - 添加带有自定义图像的新 UIButton "state"

ios - UICollectionView 仅在用户双击时调用 didSelectItemAtIndexPath,当用户单击时不会调用

swift - CollectionViewCell、MapView 和自定义注释

ios - 将 View Controller 添加到 UICollectionViewCell

ios - 使用 swift 和 objective-c 下载文件

c# - 如何使用 UIView.hidden 属性更改 View 的可见性

swift - 如何在 SKScene 中正确设置 UIButton

ios - UIButton调整宽度为文本宽度