Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate changing UILabel number of lines

I have a UILabel, listDescription, which starts off with 5 lines showing. It is grabbing a large amount of text from a database, and the total number of lines is uncertain. I've implemented a "Show More" button that, when pressed, will expand it to show the whole contents. I've gotten it working fine, however I'm hoping to add an animation for the change in height.

My code:

@IBAction func toggleDesc(sender: AnyObject) {
    if (self.listDescription.numberOfLines>0)
    {
        self.listDescription.numberOfLines=0
        self.showMoreBtn.setTitle("Show Less", forState: UIControlState.Normal)
    }
    else
    {
        self.listDescription.numberOfLines=5
        self.showMoreBtn.setTitle("Show More", forState: UIControlState.Normal)
    }
}

I've tried wrapping the numberOfLines change in UIView.animateWithDuration, but the change was still instantaneous.

My best guess is to put the label in a view, disallow overflow from that view, expand the number of lines, grab the new (unshown) height of the label, and increase the view's size. But then I wouldn't know what to do in the other direction, for shrinking it when "Show less" is tapped.

I'm open for suggestions, and will be doing some experimenting myself.

[Edit: So, I was initially concerned that if I replaced the explicit numberOfLines setting and just introduced a height constraint, the text wouldn't properly truncate at the end (... if it's too long), but it seems to do that just fine.

That said, it would be handy to be able to set the number of lines instead of the height, because I want it to seem consistent across multiple devices, even after I implement automated font-resizing based on the screen dimensions, for tablets and such.

That can be a consideration for later though. I've got a height constraint on the label, and I'm hoping that if I remove the constraint and wrap it in some animation code, it will adjust to its full size. However, I still can't quite get the code right.]

like image 603
MikeOShay Avatar asked Nov 09 '22 20:11

MikeOShay


1 Answers

You can try a few things, in the animation, use one with options and use .AllowAnimatedContent, also, modify the frame of the label in the animations, for that you will have to calculate the new height based on the text, font, font size and width.

EDIT: Added an extension to calculate the height

extension UIFont {
    func sizeOfString (string: NSString, constrainedToWidth width: Double) -> CGSize {
        return string.boundingRectWithSize(CGSize(width: width, height: DBL_MAX),
            options: NSStringDrawingOptions.UsesLineFragmentOrigin,
            attributes: [NSFontAttributeName: self],
            context: nil).size
    }
}
like image 135
Juan de la Torre Avatar answered Dec 05 '22 07:12

Juan de la Torre