Swift 动态创建的 UILabel 出现两次

Swift Dynamically created UILabel shows up twice

我写了一个自定义图形 UIView 子类,我用它来绘制一些基本数据,并插入一些用户定义的数据。作为最后一步,我想在图形顶部添加一个 UILabel,并调用用户定义的数据点。

我突出显示点,然后创建并添加 UILabel:

if(graphPoints[i] == highlightPoint){
            var point2 = CGPoint(x:columnXPoint(i), y:columnYPoint(graphPoints[i]))
            point2.x -= 8.0/2
            point2.y -= 8.0/2
            let circle2 = UIBezierPath(ovalInRect:
                CGRect(origin: point2,
                    size: CGSize(width: 8.0, height: 8.0)))
            highlightColor.setFill()
            highlightColor.setStroke()
            circle2.fill()
            let circle = UIBezierPath(ovalInRect:
                CGRect(origin: point,
                    size: CGSize(width: 5.0, height: 5.0)))
            UIColor.whiteColor().setFill()
            UIColor.whiteColor().setStroke()

            circle.fill()
            var pointLabel : UILabel = UILabel()
            pointLabel.text = "Point = \(graphPoints[i])"
            pointLabel.frame = CGRectMake(point2.x, point2.y, 100, 50)
            self.addSubview(pointLabel)
        } else {
            let circle = UIBezierPath(ovalInRect:
                CGRect(origin: point,
                    size: CGSize(width: 5.0, height: 5.0)))
            UIColor.whiteColor().setFill()
            UIColor.whiteColor().setStroke()
            circle.fill()

        }

这看起来应该可以,但是 UILabel 添加了两次。我究竟做错了什么?

此代码可能在 drawRect 中。您在 drawRect 中添加子视图是不正确的。 drawRect 在视图出现时至少被调用两次,之后可能多次调用。

您应该覆盖一些早期的生命周期方法,例如 awakeFromNib() 或构造函数。在那里,构造您的标签并将其添加为子视图。这样 addSubView() 就应该发生 一次 。没有内容的标签将是不可见的,所以不用担心。

drawRect中,只需更新标签的所有必要属性,包括frame

如果您发现您实际上需要大量来来去去的文本 "labels",每个图形的数​​量不同,毕竟您真的不希望 UILabel 作为子视图。考虑使用 someString.drawAtPoint(...)

直接在屏幕上绘制文本