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

soat7uwm  于 2023-06-25  发布在  iOS
关注(0)|答案(3)|浏览(131)

我有一个“假”复选框,我使用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)

            }
        }
    }
nhn9ugyo

nhn9ugyo1#

你可以把你的形象摆在前面

class ButtonSubclass: UIButton {
    override func awakeFromNib() {
        super.awakeFromNib()
        /**
         Set other button property and layers.
         */
        
        if let imgView = imageView {
            self.bringSubviewToFront(imgView)
        }
    }
}
xxls0lw8

xxls0lw82#

您需要在按钮的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)
}
zhte4eai

zhte4eai3#

谢谢拉贾·基尚,这对我很有效

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

相关问题