即使在0

问题描述

我使用以下代码将UIView插入UIButton中:

        let backgroundView = UIView()
        backgroundView.backgroundColor = .red
        backgroundView.translatesAutoresizingMaskIntoConstraints = false
        
        blueButton.insertSubview(backgroundView,at: 0)
        NSLayoutConstraint.activate([
            backgroundView.leadingAnchor.constraint(equalTo: blueButton.leadingAnchor),backgroundView.trailingAnchor.constraint(equalTo: blueButton.trailingAnchor),backgroundView.topAnchor.constraint(equalTo: blueButton.topAnchor),backgroundView.bottomAnchor.constraint(equalTo: blueButton.bottomAnchor)
        ])

问题是backgroundView覆盖了整个按钮,我只看到红色字段,而不是带有红色背景(我的subView)的按钮(它是图像)。

这是我图片中的故事板部分。除了尝试将subView放入之外,我没有使用此按钮在代码中进行其他操作:

enter image description here

我的目标是使圆圈背景如下图所示。例如,红色圆圈按钮的背景视图为圆形的红色(但比红色按钮亮)。按钮的标准背景应保持不变。

enter image description here

我还尝试将subView发送到后台,但是对我来说不起作用:

blueButton.sendSubviewToBack(backgroundView)

我减小了子视图的alpha值,以查看按钮图像是否仍然存在。

for view in blueButton.subviews {
    view.alpha = 0.5
}

它是:

enter image description here

我该如何解决这个问题?

解决方法

请勿将额外的子视图插入按钮。如果目标是使按钮的背景色为红色,请将其backgroundColor设置为.red。如果目标是在按钮图像后面放置一些东西,那就是backgroundImage的目的。或者只是使按钮图像看起来像您真正想要的图像。

我按下了此按钮:

enter image description here

它看起来很像您的图片。这是代码:

let im = UIGraphicsImageRenderer(size: CGSize(width: 30,height: 30)).image {
    ctx in
    UIColor.red.withAlphaComponent(0.2).setFill()
    ctx.cgContext.fillEllipse(in: CGRect(x: 0,y: 0,width: 30,height: 30))
    UIColor.red.setFill()
    ctx.cgContext.fillEllipse(in: CGRect(x: 5,y: 5,width: 20,height: 20))
}
b.setImage(im.withRenderingMode(.alwaysOriginal),for: .normal)

我认为这比弄乱不需要的非法子视图要好得多。