如何在 UILabel 的文本下绘制内容?

How do I draw stuff under the text of a UILabel?

我创建了一个自定义 UILabel 子类,中间有一个圆圈,标签文本(数字)将位于圆圈上方。

我最初想用 layer.cornerRadius 来做这个,但是当标签的宽度和高度不相等时,这不会创建一个圆。

我的意思是,对于宽度为 100 高度为 50 的标签,我仍然想要一个半径为 50 且中心位于 (50, 25) 的圆。

因此,我尝试用UIBezierPath画圆。这是我试过的:

override func draw(_ rect: CGRect) {
    super.draw(rect)
    if bounds.height > bounds.width {
        let y = (bounds.height - bounds.width) / 2
        let path = UIBezierPath(ovalIn: CGRect(x: 0, y: y, width: bounds.width, height: bounds.width))
        circleColor.setFill()
        path.fill()
    } else {
        let x = (bounds.width - bounds.height) / 2
        let path = UIBezierPath(ovalIn: CGRect(x: x, y: 0, width: bounds.height, height: bounds.height))
        circleColor.setFill()
        path.fill()
    }
}

我放了 super.draw(rect) 因为我认为那会绘制标签的文本,但是当我 运行 应用程序时,我只看到圆圈而不是我的标签文本。

我很困惑,为什么super.draw(rect)没有绘制标签的文字?

看不到文本,因为 UIBezierPath 的 "z-index" 取决于它们的绘制顺序。换句话说,UIBezierPath 个画在彼此之上。

super.draw(rect) 确实绘制了文本。但是当你把它作为第一条语句时,它会首先绘制,所以你之后绘制的所有内容都会位于文本之上。要解决此问题,您应该最后调用 super.draw(rect):

override func draw(_ rect: CGRect) {
    if bounds.height > bounds.width {
        let y = (bounds.height - bounds.width) / 2
        let path = UIBezierPath(ovalIn: CGRect(x: 0, y: y, width: bounds.width, height: bounds.width))
        circleColor.setFill()
        path.fill()
    } else {
        let x = (bounds.width - bounds.height) / 2
        let path = UIBezierPath(ovalIn: CGRect(x: x, y: 0, width: bounds.height, height: bounds.height))
        circleColor.setFill()
        path.fill()
    }
    super.draw(rect) // <------- here!
}

或者,只需继承 UIView,在 draw(_:) 中绘制圆圈,然后添加 UILabel 作为其子视图。这种方法的优点是它不依赖于 super.draw(_:) 的实现,这在未来可能会改变,