gpt4 book ai didi

ios - draw() 的 Swift 回调函数?

转载 作者:行者123 更新时间:2023-11-28 15:19:39 25 4
gpt4 key购买 nike

我有一个 customView,我在其中覆盖了 drawRect: .我也有一些情况,我想在我的 customView 上显示一个 UILabel:

if self.ticks.count < 50 {
self.label.frame = self.bounds
self.label.text = "This chart requires 50 or more ticks.\nKeep Ticking."
self.addSubview(label)
}

但是,如果我在 drawRect 之前调用此代码被调用,那么我的标签就不会出现。有没有类似viewDidDraw之类的回调方法?

编辑

有人要求它,所以这里是所有正在做我需要它做的事情的代码。我认为问题的答案是覆盖 layoutSubviews

@IBDesignable open class  CustomView: UIView {
@objc open var ticks:[Tick] = []
let label = UILabel()

required public init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
required public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
func setup(){
self.backgroundColor = UIColor.clear
self.label.frame = self.bounds
self.label.text = "This chart requires 50 or more ticks.\nKeep Ticking."
self.label.numberOfLines = 0
self.label.textAlignment = .center
self.addSubview(label)
}

override open func layoutSubviews() {
self.label.frame = self.bounds
}

@objc open func setSessions(sessions:[Session]){
self.ticks = []
for session in sessions.reversed(){
if self.ticks.count < 250{
self.ticks = self.ticks + (session.getShots() as! [Shot])
}else{
break
}
}
if self.ticks.count < 50 {
self.label.isHidden = false
}else{
self.label.isHidden = true
}
self.bringSubview(toFront: self.label)
}

override open func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()!
let width = rect.width - 10;
let height = rect.height - 10;
let center = CGPoint(x: width/2+5, y: height/2+5)
let big_r = min(width, height)/2

context.setLineWidth(1.5)
UIColor.white.setStroke()

//draw the rings
for i in stride(from: 1, to: 7, by: 1){
let r = big_r * CGFloat(i) / 6.0;
context.addArc(center:center, radius:r, startAngle: 0, endAngle: CGFloat(2*Double.pi), clockwise: false)
context.strokePath()
}

//draw the ticks
if self.ticks.count > 49 {
UIColor.red().setFill()
for (i, tick) in self.ticks.prefix(250).enumerated(){
let radius = min((100.0-CGFloat(shot.score))/30.0 * big_r, big_r);

let x = Utilities.calculateX(tick, radius)
let y = Utilities.calculateY(tick, radius)

let point = CGPoint(x: x+center.x,y: y+center.y)
context.addArc(center:point, radius:CGFloat(DOT_WIDTH/2), startAngle: 0, endAngle: CGFloat(2*Double.pi), clockwise: false)
context.fillPath()
}
}
}
}

最佳答案

您可以在需要时通过调用 setNeedsDisplay() 来重绘自定义 View 。之后,您可以添加标签

关于ios - draw() 的 Swift 回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46244929/

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