UILabel autolayout usage: The child control determines the height of the parent control, uilabelautolayout
Today, let's talk about the usage of UILable autolayout. This control is a bit special. If you do not set it, you just set the text content on the UILable, and you will find that the text content cannot be filled with the entire UILable,
If this happens, it will be embarrassing. Today we will talk about how to fill the entire label with text. We now have a requirement that the parent control increase and decrease as the height of the Child control increases. Please take a look at the effect first:
Now I will take you through this demo. First, create a project and drag it to the top textField in Main. storyboard. We will constrain it,
Then we pull a UIView and constrain it:
In this case, there is obviously a problem, because we need to make the height change with the height of the Child control, so we cannot restrict its height, currently, only the top, left, and right aspects of the view can be restricted. Then, drag an imageView above to give a blue background color and constrain it:
Next is the most critical UILabel. Give it a red background color.
The constraint on the control is basically completed, so the maximum text width in the label is that the width of the parent control is reduced by 20.LabelYou can increase the length of the text until the maximum width. The height of the yellow view increases and decreases with the height of the label, thus achieving the effect, the subsequent work is much simpler. Get UILabel and UITextfield and directly run the Code:
#import "ViewController.h"@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *label;@property (weak, nonatomic) IBOutlet UITextField *textField;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; self.textField.delegate = self;}- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string]; [UIView animateWithDuration:1.0 animations:^{ self.label.text = text; [self.view layoutIfNeeded]; }]; return YES;}
@end
Remember
[Self. viewLayoutIfNeeded];This code is especially important. Without this code, there is no animation effect. Remember the omnipotent formula.
Each constraint corresponds to the following relationship:
FirstItem. firstAttribute {=, <=, >=} secondItem. secondAttribute * multiplier + constant
Multiplier: Proportional Coefficient
Constant: a constant.
Attribute: Layout Attribute
Now, the sharing is over.