IOS: Adjust UIButton height depend on title text using Autolayout?

前端 未结 4 1799
囚心锁ツ
囚心锁ツ 2021-01-02 12:40

I have a UIButton and it can change the title at the runtime. Therefore, I want to increase the UIButton height depend on the title text for displa

4条回答
  •  走了就别回头了
    2021-01-02 13:15

    There is a way I always used:

    1. Add another reference UILabel which lineNumber=0 and the same width with the target button.
    2. Do not set height constraint for the ref-UILable, and should set a height constraint for the button to adjust its height
    3. Set the same text to the ref UILabel with the button.titleLable, sizeTofit it and get its frame.size.height
    4. Use the height value to the height constraint of the target button. (Of course, the button.titleLabel linenumber should be set to 0 or more lines)

    Done. :)

    PS1. This way can be used for the button and ref-label in a scrollview.

    PS2. In some case, we can not get the correct height of the ref-label because it cannot gain a correct frame.width in scrollview, especially when we use the trailling constraint. We could consider to define a fixed width to the ref-label before sizeTofit and obtain the correct height for target button use.

提交回复
热议问题