无法从黑色更改 UIView 背景颜色

Cant Change UIView Background Color From Black

这是我第一次遇到 drawRect 问题。我有一个简单的 UIView 子类,其中包含要填充的路径。一切都很好。路径被正确填充,但无论如何背景仍然是黑色。我应该怎么办?我的代码如下:

var color: UIColor = UIColor.red {didSet{setNeedsDisplay()}}

private var spaceshipBezierPath: UIBezierPath{
    let path = UIBezierPath()
    let roomFromTop: CGFloat = 10
    let roomFromCenter: CGFloat = 7
    path.move(to: CGPoint(x: bounds.minX, y: bounds.maxY))
    path.addLine(to: CGPoint(x: bounds.minX, y: bounds.minY+roomFromTop))
    path.addLine(to: CGPoint(x: bounds.midX-roomFromCenter, y: bounds.minY+roomFromTop))
    path.addLine(to: CGPoint(x: bounds.midX-roomFromCenter, y: bounds.minY))
    path.addLine(to: CGPoint(x: bounds.midX+roomFromCenter, y: bounds.minY))
    path.addLine(to: CGPoint(x: bounds.midX+roomFromCenter, y: bounds.minY+roomFromTop))
    path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.minY+roomFromTop))
    path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.maxY))
    path.addLine(to: CGPoint(x: bounds.minX, y: bounds.maxY))
    return path
}

override func draw(_ rect: CGRect) {
    color.setFill()
    spaceshipBezierPath.fill()
}

视图如下所示:

I have a simple UIView subclass ... but the background remains black no matter what

通常这种情况是因为您忘记将 UIView 子类的 isOpaque 设置为 false。最好在 UIView 子类的初始化程序 中 执行此操作,以便它足够早。

例如,我在这里对您的代码进行了非常轻微的调整。这是我使用的完整代码:

class MyView : UIView {
    private var spaceshipBezierPath: UIBezierPath{
        let path = UIBezierPath()
        // ... identical to your code
        return path
    }
    override func draw(_ rect: CGRect) {
        UIColor.red.setFill()
        spaceshipBezierPath.fill()
    }
}

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()        
        let v = MyView(frame:CGRect(x: 100, y: 100, width: 200, height: 200))
        self.view.addSubview(v)
    }
}

注意黑色背景:

现在我将这些行添加到 MyView:

override init(frame:CGRect) {
    super.init(frame:frame)
    self.isOpaque = false
}
required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

看到不同之处了吗?

对于未来的求职者....

我遇到了同样的问题,但@matt 的解决方案对我不起作用。

在我的场景中,我有一个 UIView (A) 在另一个 UIView (B) 后面。 UIView (A) 有一个 背景颜色 而 UIView (B) 是透明的。值得注意的是,B 被子类化以通过覆盖 draw 方法使用 UIBezier 创建自定义形状。

事实证明,在这种情况下,透明的 UIView 毫无意义,我不得不为 B 设置相同的背景颜色,或者删除 A 的背景颜色。

没有别的办法了,有相同的场景就别浪费时间了!

在我的例子中,我解决的问题是从 Background-Color“无颜色”切换到 Background-Color“清晰颜色”