Smart caption by UILabel or UITextView

155 Views Asked by At

I would like to create a smart caption as SoundCloud app did. See the attachment below,

enter image description here

These two captions: - •PAN• - Berlin, Germany

are what I want create.

These captions seem to be executed by sizeToFit or sizeThatFits. However, if using sizeThatFits with background colour (by NSBackgroundColorAttributeName), you won't get padding both before the first and after the last letters and top and bottom paddings as well. The caption will be organised the exact fit size as these letters.

enter image description here

Anyway, what I would like to do is the exact same caption like the attachment picture.

Cheers,

2

There are 2 best solutions below

1
On

You have two approaches here. One is to add a bit of padding after calling sizeThatFits. The other is to prepend and append a space to your label title.

The right way about adding the padding, though, would be to extend UILabel and on your subclass, override the method textRectForBounds:limitedToNumberOfLines:. In there, just call the same method on super passing the bounds you receive, only smaller.

0
On

I know is an old question but i was looking for the same effect that SoundCloud has on its labels. here is the subclassing of uilabel

    import UIKit

    class LabelPine: UILabel {

override func drawTextInRect(rect: CGRect) {
    let insets = UIEdgeInsets.init(top: 5, left: 0, bottom: 5, right: 3)
    super.drawTextInRect(UIEdgeInsetsInsetRect(rect, insets))
}

override func textRectForBounds(bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
    super.textRectForBounds(bounds, limitedToNumberOfLines: 0)

    return CGRectInset(self.attributedText!.boundingRectWithSize(CGSizeMake(999, 999), options: .UsesLineFragmentOrigin, context: nil), -5, -5)




    }
}

And here is the implementation on the respective class:

   labelNombre = LabelPine()
    labelNombre?.text = nombreUser
    labelNombre?.frame = CGRectMake(10, nombrePos.Yo, nombrePos.ancho, nombrePos.alto)
    labelNombre?.font = UIFont(name:"Hiragino Sans W3",size: 19)!
    labelNombre?.textAlignment = .Left
    labelNombre?.backgroundColor = UIColor(white: 1, alpha: 0.5)
    labelNombre?.textColor = colorBlentUIColor
    labelNombre?.sizeToFit()

    header?.addSubview(labelNombre!)

Take notice i call sizeToFit().