UILabel Subclass - Custom' drawRect'方法导致文本被切断/不显示

时间:2016-03-19 23:34:25

标签: autolayout uilabel tooltip drawrect drawtextinrect

我正在创建一个简单的工具提示'子类,它是一个圆角矩形和一个小三角形,将被“锚定”#39;另一种观点。

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

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

这一切都很有效,除了我无法在“RoundRect”中显示全文。似乎文本不会显示在最后一行(即三角形现在占据的位置)。

另外需要注意的一点是,我正在使用自动布局并为“工具提示”设置了约束。根据需要填写屏幕。这可以按预期工作,因为减少/添加更多文本会显示相应大小的工具提示。但似乎我需要以某种方式通知工具提示'或者'自动布局'该文本应该适用于'roundRect' “工具提示”的一部分'。

屏幕截图#1使用了这个' drawTextInRect'方法,您可以看到正在显示全文,但重叠到“三角形”中。区域(加上它没有插入物,这不是所需的外观):

    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,以便不用文本写入空格),你可以看到它切断了第2行和第3行文本,因为它们不适合&#39 ;在' roundRect'界限:

    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)
}

Screenshot #1 Screenshot #2

1 个答案:

答案 0 :(得分:1)

我实际上不会为此子类化UILabel,并使用自动布局约束创建由外部视图和内部标签组成的自己的工具提示类。内部标签决定了视图的整个高度。

这样的东西有适当的圆角/三角形: enter image description here

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