简体   繁体   中英

How do I create a SubView that pops up dynamically and expands it's superview size. (in code)

So I currently have a UIView subclass called: " InputView " with two subviews, a UILabel and a UITextField . The way i've set it up is I can change the label and text field placeholder so that this InputView can serve as a modular component for any input field in my app (email, password, etc.) All I have to do is create an empty UIView in my storyboard, set it's class as InputView , and have the rest be done programmatically.

Now, I'm running into an issue. The InputView 's are plain UIView 's whose constraints are set in the storyboard, but I want to add a subview (a table) that appears/disappears dynamically whenever a user is editing the UITextField . Every time the table appears, the InputView expands in height, pushes everything below it down, and then disappears very neatly afterward.

I have no idea how to do that. Here is what I've thought of doing:

Idea 1: Place the table in the view, add all necessary constraints to it and hope InputView expands by itself. This lead to the table being outside the frame of the InputView , and therefore unresponsive to user touches for some reason

Idea 2: Change the bounds of the InputView and expand it's height by the table's height. This doesn't work because the constraints are set in the storyboard and I don't have access to them programmatically

Idea 3: After almost 5 hours of research and failed attempts, go to StackOverflow and see if someone has an idea how to fix it. (Thanks!)

You can set things up so that your storyboard constraints can be changed programmatically.

1) In the storyboard, set a height constraint for inputView and set it to the value that makes sense for when the table is not visible -- probably around 30. (You have probably already done this.)

2) Then create an outlet to your code by control-dragging that height constraint to the file that corresponds to the view controller that has inputView in it. A dialog box will prompt you to give the outlet a name in your code. Call it something like inputViewHeightConstraint .

3) Then in your code, when you want to make your inputView have a bigger height, set inputViewHeightConstraint.constant to a new value. Note you need to refer to .constant in order to set the new height of the constraint.

When you first set your height constraint for inputView, be sure to make it an "equals" constraint (eg, its height equals 30) rather than a "greater than or equals" constraint. Even though the latter would make more sense since you'll be changing it to a greater value in your code, I've found there are bugs with that approach. Making it a straight "equals" constraint works more cleanly.

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