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

标签 ios swift uiview uibezierpath

我创建了一个自定义 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 作为其 subview 。这种方法的优点是它不依赖于 super.draw(_:) 的实现,该实现将来可能会发生变化,

关于ios - 如何在 UILabel 的文本下绘制内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54015404/

相关文章:

ios - 将嵌套在容器 View Controller 中的 UINavigationController 添加到 UITabBarController

ios - 延迟后触发具有 2 个参数的函数

swift - 从 Async F# 在主线程上执行代码

swift - 无法形成对 NSTextView 类实例的弱引用

Swift 编译不使用预编译头文件

ios - UIScrollView 和 touchesBegan/touchesEnded 等

ios - 如何将具有动态高度的 xib subview 添加到 UIView

ios - xcode 尝试使用图像设置后退按钮

ios - Swift 4,加载下一个 ViewController

ios - 界面生成器未在 Xcode 9 中打开