gpt4 book ai didi

ios - 自定义 UIView 中的无效上下文 0x0 - 后续问题

转载 作者:行者123 更新时间:2023-11-28 11:47:37 26 4
gpt4 key购买 nike

这篇文章: invalid context 0x0 within custom UIView...应该给我解决问题的关键,但我无法避免无效上下文错误。一些澄清将不胜感激。

我想在 ViewController 加载时显示的 subview 中画线。为此,我为 UIView 创建了一个子类,它类似于 StartPlayer 发布的 SplitCircleView。

要运行代码,请创建一个新项目并将 ViewController 文件的内容替换为:

import UIKit
@IBDesignable

class ViewController: UIViewController {
let mySubViewInstance = SplitCircleView()

override func viewDidLoad() {
super.viewDidLoad()

//let mySubViewInstance = SplitCircleView()
mySubViewInstance.setNeedsDisplay(mySubViewInstance.frame)
}
}

class SplitCircleView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
//self.setNeedsDisplay()
//draw(frame)
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
//self.setNeedsDisplay()
//draw(frame)
}

override func setNeedsDisplay(_ rect: CGRect) {
self.backgroundColor = .clear

drawSlice(rect: rect, startPercent: 87.5, endPercent: 37.5, color: .green)
drawSlice(rect: rect, startPercent: 37.5, endPercent: 87.5, color: .red)
}

func drawSlice(rect: CGRect, startPercent: CGFloat, endPercent: CGFloat, color: UIColor) {
let center = CGPoint(x: rect.origin.x + rect.width / 2, y: rect.origin.y + rect.height / 2)
let radius = (min(rect.width, rect.height) / 2)
let startAngle = startPercent / 100 * .pi * 2 - .pi
let endAngle = endPercent / 100 * .pi * 2 - .pi
let path = UIBezierPath()

path.move(to: center)
path.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
path.close()
color.setFill()
path.fill()
}
}

如何避免无效上下文错误并在加载 ViewController 时在 subview 中绘制内容?

最佳答案

您应该覆盖 draw,而不是 setNeedsDisplay

override func draw(_ rect: CGRect) {
self.backgroundColor = .clear

drawSlice(rect: rect, startPercent: 87.5, endPercent: 37.5, color: .green)
drawSlice(rect: rect, startPercent: 37.5, endPercent: 87.5, color: .red)
}

背景颜色的设置只需要设置一次,所以 draw 并不是该行的理想位置。将其移动到 init

setNeedsDisplay 表示绘图需要更新。但实际绘制的是 draw

关于ios - 自定义 UIView 中的无效上下文 0x0 - 后续问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52318432/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com