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

我有一个按钮,我放在自定义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)
    }

这导致以下结果:

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

我还以为使用.withRenderingMode(.alwaysOriginal)应该已经完成​​了这个伎俩,但没有运气.

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

解决方法

UIView的子视图是视图主CALayer中的图层,显然是 no way to bring them above the layer,因为这就像将它们带出视图一样.

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

或者,您可以插入背景子图层,并将边框应用于此图层.但是,请注意不要添加子层,因为它会添加到子视图上方,但是要将它插入到索引0以便它在后面

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

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

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...