我有一个按钮,我将其放置在自定义 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
的 subviews
是 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/