当我不希望它成为时,UIButton 是透明的
Posted
技术标签:
【中文标题】当我不希望它成为时,UIButton 是透明的【英文标题】:UIButton is transparent when I don't want it to be 【发布时间】:2018-09-19 11:39:46 【问题描述】:我有一个按钮放在自定义 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)
应该可以解决问题,但没有运气。
关于为什么会发生这种情况的任何想法?
【问题讨论】:
向 UICollectionViewCell 的 contentView 属性添加视图 你有alpha小于1的view吗 @Shruti 不,我没有 @aleixrr 这并不能解决问题。实际上没有任何变化 【参考方案1】:UIView
的subviews
是视图的主要CALayer
内的层,而且显然还有no way to bring them above the layer,因为这就像将它们带出视图。
您可以添加一个带边框的背景子视图,并在其前面添加所有其他视图。
或者,您可以插入背景子图层,并为该图层应用边框。但是,请注意不要addSublayer
,因为它会添加到子视图上方,而是将其插入到索引 0 处,使其位于后面
let backgroundLayer = CALayer()
backgroundLayer.frame = layer.bounds
backgroundLayer.borderColor = UIColor.lightGray.cgColor
backgroundLayer.borderWidth = 1.0
layer.insertSublayer(backgroundLayer, at: 0)
另一个需要注意的重点是确保插入层代码不会被重复调用。
【讨论】:
就是这样。简洁和我需要的。谢谢。以上是关于当我不希望它成为时,UIButton 是透明的的主要内容,如果未能解决你的问题,请参考以下文章