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

查看:130
本文介绍了无法从黑色更改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()
}

这是视图的样子:

Here is what the view looks like:

推荐答案


我有一个简单的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天全站免登陆