简体   繁体   中英

how to expand and collapse UILabel?

So I am trying to build a little expand and collapse UILabel like the one you see below. There would also be some text below it. When you touch the heading it should show you more less of the text.

I understand that I can set the number of lines to zero of the text label and it will figure out how much height it needs to show the whole text. My initial approach was change the number of lines from zero to say three, and then I do something like the code below...

    `UIView.animate(withDuration: 0.4) {
        self.body.superview?.layoutIfNeeded()
    }`

this technically works, but the animation looks terrible. It looks jumpy for the lack of better word, so I am think I might have to animate the height instead. So how can I actually calculate the needed height of the text if I don't know how long it will? I can animate the height from say 65 (some arbitrary number) to whatever the height it needs to be.

在此处输入图片说明

Yes, you can. You need to set a constraint for the height and change it's constant, (or you can set 2 constraints and change the priority, just make sure the priorities are not 0 a 1000, but 1 and 999. You cannot change them otherwise). Do it before the animation block you have and keep it as it is.

I have a pod that allows you to do 99% of this from the storyboard

https://github.com/fer662/FMConstraintSwitch

You drop a FMStateConstraintSwitch on your storyboard, set the outlets for the constraints, and the parent view that needs to be laid out. Then from your code you just change the state on the FMStateConstraintSwitch. It can switch more than 1 constraint for each state.

The easy way:

Create StackView with two labels inside. First label for title, second for text - hidden by default.

Now on tap action just do this:

UIView.animate(withDuration: 0.5) { 
    self.textLabel.isHidden = false
}

With StackView the animations is for free :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM