UITextView autolayout 高度自适应

UITextView *t = [[UITextView alloc] initWithFrame:CGRectMake(20, 0, [UIScreen mainScreen].bounds.size.width - 40, 100)];
    t.backgroundColor = [UIColor yellowColor];
    t.text = @"11111111111111的方法的事发生的事的方法的事发生的事的方法的事发生的事的方法的事发生的事的方法的事发生的事的方法的事发生的事的方法的事发生的事的方法的事发生的事的方法的事发生的事的方法的事发生的事的方法的事发生的事的方法的事发生的事的方法的事发生的事的方法的事发生的事的方法的事发生的事的方法的事发生的事的方法的事发生的事的方法的事发生的事";
    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;

猜你喜欢

转载自hulefei29.iteye.com/blog/2276553
今日推荐