context.fill() 没有出现 Swift 4 Xcode 10

context.fill() doesn't show up Swift 4 Xcode 10

我正在尝试从 firebase 读取数据并根据 firebase 中的数据绘制矩形。颜色也将相应地填充从 Firebase 检索到的值。我已经设法从 firebase 检索数据并将它们附加到数组中。

由于 Firebase 是异步的,我在 readMarina() 完成后仅将完成处理程序添加到 运行 以下代码。我正在尝试通过输入矩形框的简单绘图来测试 draw() 方法中的 readMarina{}。一切 运行 都很顺利,直到 context?.fill(lot) 出现错误:

"Thread 1: EXC_BAD_ACCESS (code=1, address=0x7ffe00000058)"

override func draw(_ rect: CGRect)
{
    let context = UIGraphicsGetCurrentContext()
    let lot = CGRect(x: 80,y: 20,width: 30,height: 60)

    readMarina{
        context?.addRect(lot)
        context?.setFillColor(UIColor.red.cgColor)
        context?.fill(lot)
    }
}

func readMarina (_ completion: (() -> Void)?){
    let ref = Database.database().reference()
    let cpDB = ref.child("CarPark")
    cpDB.child("MarinaSq").observe(.value, with: {snapshot in

        let snapshotValue = snapshot.value as! Dictionary<String, AnyObject>

            for (key, value) in snapshotValue 
            {
                if (self.lot.count)<((snapshotValue.count)){
                    let v = value as! String
                    let k = key

                    self.lot.append(k)
                    self.status.append(v)
                }
            }
            completion?()
     }) 
}

我尝试调试,当我将鼠标悬停在 "context" 和 "context?" 上时,它们都显示了一个值。当我将鼠标悬停在 "lot" 上时,也有解析的值。我的代码有什么问题,为什么我的矩形框没有出现在我的视图中?

A picture of the error message

正如 draw(_ rect: CGRect) 函数描述所说:

This method is called when a view is first displayed or when an event occurs that invalidates a visible part of the view. You should never call this method directly yourself. To invalidate part of your view, and thus cause that portion to be redrawn, call the setNeedsDisplay() or setNeedsDisplay(_:) method instead.

您在 draw(_ rect: CGRect) 函数内部的闭包会干扰其执行过程,很可能会导致崩溃。要处理此问题,您应该从 draw(_ rect: CGRect) 内部删除 readMarina 函数调用。这是一个简单的实现:

class MyView: UIView {

    var myColor: UIColor? {
        didSet {
            setNeedsDisplay()
        }
    }

    override func draw(_ rect: CGRect) {
        if let context = UIGraphicsGetCurrentContext(), let color = myColor {
            let lot = CGRect(x: bounds.midX-50, y: bounds.midY-50, width: 100, height: 100)
            context.addRect(lot)
            context.setFillColor(color.cgColor)
            context.fill(lot)
        }
    }

}

我在 Main.storyboard 中向我的 ViewController 添加了一个视图,并在身份检查器中将自定义 class 设置为 "MyView"。

 class ViewController: UIViewController {

    @IBOutlet weak var myView: MyView!

    override func viewDidLoad() {
        super.viewDidLoad()
            testFunc {
                self.myView.myColor = UIColor.red
            }
    }

    func testFunc(completion:(() -> Void)?) {
        // test func
        completion?()
    }
}