无法从黑色更改 UIView 背景颜色 [英] Cant Change UIView Background Color From Black

查看:28
本文介绍了无法从黑色更改 UIView 背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is my first time in which I've encountered problems with drawRect. I have a simple UIView subclass with a path to fill. Everything is fine. The path gets filled properly, but the background remains black no matter what. What should I do? My code is listed below:

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()
}

这里是视图的样子:

推荐答案

我有一个简单的 UIView 子类......但无论如何背景都是黑色的

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

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

Typically that sort of thing is because you have forgotten to set the UIView subclass's isOpaque to false. It is a good idea to do this in the UIView subclass's initializer in order for it to be early enough.

例如,在这里我对您的代码进行了很小的调整.这是我正在使用的完整代码:

For example, here I've adapted your code very slightly. This is the complete code I'm using:

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:

Now I add these lines to MyView:

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

看到不同之处了吗?

这篇关于无法从黑色更改 UIView 背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆