UITextView autolayout height adaptive

UITextView *t = [[UITextView alloc] initWithFrame:CGRectMake(20, 0, [UIScreen mainScreen].bounds.size.width - 40, 100)];
    t.backgroundColor = [UIColor yellowColor];
    t.text = @"111111111111111 The method of the thing happened the method of the thing happened the method of the thing happened the method of the thing happened the method of the thing happened the method of the thing happened how things happen how things happen methods of things happen methods of things happen methods of things happen The way things happen the way things happen the way things happen the way things happen
    t.translatesAutoresizingMaskIntoConstraints = NO;
    [v addSubview:t];
    
    [v addConstraint:[NSLayoutConstraint constraintWithItem:t attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:v attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0]];
    [v addConstraint:[NSLayoutConstraint constraintWithItem:t attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:v attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0]];
    [v addConstraint:[NSLayoutConstraint constraintWithItem:t attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:v attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]];
    NSLayoutConstraint *c = [NSLayoutConstraint constraintWithItem:t attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:t.contentSize.height];
    [t addConstraint:c];
    CGSize sizeThatFitsTextView = [t sizeThatFits:CGSizeMake([UIScreen mainScreen].bounds.size.width - 40, MAXFLOAT)];
    
    c.constant = sizeThatFitsTextView.height;

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327029752&siteId=291194637