UILabel 子类 - 自定义 'drawRect' 方法导致文本被截断/不显示

UILabel Subclass - Custom 'drawRect' method causes text to cut off / not show

我正在创建一个简单的 'tooltip' 子类,它是一个圆角矩形和一个 'anchored' 到另一个视图的小三角形。

我创建了一个 UILabel 子类并覆盖 'drawRect' 以缩小主标签区域并绘制一个三角形。

'roundRect' 表示应包含全文的圆角矩形部分。

这一切都很好,除了我无法在 'roundRect' 中显示全文。似乎文本没有显示在最后一行(即三角形现在占据的位置)。

还有一件事要注意,我正在使用自动布局并设置了 'tooltipLabel' 的约束以根据需要填充屏幕。这按预期工作,因为 reducing/adding 更多文本显示了适当大小的工具提示。但似乎我需要以某种方式通知 'tooltip' 或 'auto layout' 文本应该适合 'tooltipLabel'.

的 'roundRect' 部分

屏幕截图 #1 使用此 'drawTextInRect' 方法,您可以看到正在显示全文,但重叠到 'triangle' 区域(而且它没有插图,这不是我们想要的看):

    override public func drawTextInRect(rect: CGRect) {
        super.drawTextInRect(rect)
//        super.drawTextInRect(UIEdgeInsetsInsetRect(rect, UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)))
    }

屏幕截图 #2 使用此 'drawTextInRect' 方法和所需的插图(还添加了 triangleHeight 以便 space 不会写入文本)并且您可以看到它切断了第二个和第 3 行文本,因为它们不在 'roundRect' 范围内 'fit':

    override public func drawTextInRect(rect: CGRect) {
//        super.drawTextInRect(rect)
        super.drawTextInRect(UIEdgeInsetsInsetRect(self.roundRect, UIEdgeInsets(top: 10, left: 10, bottom: 10+self.triangleHeight, right: 10)))
    }

这是 'drawRect' 覆盖:

override public func drawRect(rect: CGRect) {
    self.roundRect = CGRect(x: rect.minX, y: rect.minY, width: rect.width, height: rect.height-self.triangleHeight)
    self.triangleBezier.moveToPoint(CGPoint(x: self.roundRect.midX-self.triangleWidth/2, y: self.roundRect.maxY))
    self.triangleBezier.addLineToPoint(CGPoint(x: rect.midX, y: rect.maxY))
    self.triangleBezier.addLineToPoint(CGPoint(x: self.roundRect.midX+self.triangleWidth/2, y: self.roundRect.maxY))      

    self.triangleBezier.closePath()
    self.roundRectBezier = UIBezierPath(roundedRect: self.roundRect, cornerRadius: 5.0)
    self.roundRectBezier.appendPath(self.triangleBezier)
    self.tooltipColor.setFill()
    self.roundRectBezier.fill()

    super.drawRect(rect)
}

我实际上不会为此子 classing UILabel,而是制作您自己的工具提示 class 由外部视图和具有自动布局约束的内部标签组成。内部标签决定了整个视图的高度。

像这样经过适当四舍五入的东西 corners/triangle:

或者,如果您想分配填充,请改用 UITextView:Adding space/padding to a UILabel