UIKit-添加图层效果到按钮删除图像



我有一个"假的";复选框,我使用UIButton和:

var mCheckState: Bool = false {
didSet {
if mCheckState == true {
self.setImage(checkedImage, for: UIControl.State.normal)
} else {
self.setImage(uncheckedImage, for: UIControl.State.normal)
}
}
}

但是当我创建这个图层样式来添加阴影/高光边缘时:

contentHorizontalAlignment = .left;
contentEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0);
setTitleColor(.black, for: UIControl.State.normal)
setTitleColor(UIColor(red: 0.85, green: 0.70, blue: 0.65, alpha: 1.0), for: UIControl.State.highlighted)
layer.backgroundColor = globalColorCG_white_background
layer.shadowColor = CGColor(gray: 1.0, alpha: 1.0)
layer.shadowOpacity = 0.8
layer.shadowRadius = globalButtonRadiusShadow * 0.75
layer.cornerRadius = globalButtonRadiusShadow
layer.shadowOffset = CGSize(width: -6.0,height: -8.0)
layer2 = CALayer(layer: layer)
layer2!.backgroundColor = globalColorCG_white_background
layer2!.shadowColor = CGColor(gray: 0.0, alpha: 1.0)
layer2!.shadowOpacity = 0.1
layer2!.shadowRadius = globalButtonRadiusShadow * 0.5
layer2!.cornerRadius = globalButtonRadiusShadow
layer2!.shadowOffset = CGSize(width: 6.0, height: 8.0)
layer2!.frame = layer.bounds
layer.insertSublayer(layer2!, at: 0)
showsTouchWhenHighlighted = true

图像不再渲染。我应该添加/修复什么才能再次渲染图像?:-(

额外的信息代码:

let checkedImage = UIImage(systemName: "checkmark.square")! as UIImage
let uncheckedImage = UIImage(systemName: "square")! as UIImage
var mIsCheckBox = false
var mCheckState: Bool = false {
didSet {
if mCheckState == true {
self.setImage(checkedImage, for: UIControl.State.normal)
//self.bringSubviewToFront(checkedImage)
} else {
self.setImage(uncheckedImage, for: UIControl.State.normal)
//self.bringSubviewToFront(uncheckedImage)
}
}
}

您可以将图像放在前面

class ButtonSubclass: UIButton {
override func awakeFromNib() {
super.awakeFromNib()
/**
Set other button property and layers.
*/

if let imgView = imageView {
self.bringSubviewToFront(imgView)
}
}
}

您需要在按钮的ImageView层下方添加layer2

所以更改这一行:

layer.insertSublayer(layer2!, at: 0)

对此:

layer.insertSublayer(layer2!, below: imageView!.layer)

你可能想检查一下按钮的imageView不是nil,在它只是添加的情况下,就像你已经添加的一样:

if let imageViewLayer = imageView?.layer {
layer.insertSublayer(layer2!, below: imageViewLayer)
} else {
layer.insertSublayer(layer2!, at: 0)
}

感谢Raja Kishan,它为我工作

// bring button's image view to the front, self here is UIButton
if let imageView = self.imageView {
self.bringSubviewToFront(imageView)
}
self.layoutIfNeeded()

最新更新