How to calculate TextView height base on text

前端 未结 6 2060
無奈伤痛
無奈伤痛 2021-01-05 02:43

I am using the code below for calculate the height of text, then set this height for UILabel and UITextView

CGSize targetSize = CGS         


        
6条回答
  •  死守一世寂寞
    2021-01-05 03:08

    There are two things you can try:

    1. Set textView.textContainerInset = UIEdgeInsetsZero
    2. Set textView.textContainer.lineFragmentPadding = 0

    With these operations you can get rid of all the padding in the textView and when its width matches with the label's one the heights are also the same.

    Here's a sample code you can place in an empty viewController and test it yourself:

    - (void)viewDidAppear:(BOOL)animated {
        [super viewDidAppear:animated];
    
        NSString *text = @"The internet connection appears to be offline.";
        CGFloat width = 100.f;
    
        UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20, 20, width, 300)];
        textView.font = [UIFont fontWithName:@"AvenirNext-Regular" size:12.f];
        textView.text = text;
        [self.view addSubview:textView];
    
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20 + width, 20, width, 300)];
        label.numberOfLines = 0;
        label.font = [UIFont fontWithName:@"AvenirNext-Regular" size:12.f];
        label.text = text;
        [self.view addSubview:label];
    
        // Getting rid of textView's padding
        textView.textContainerInset = UIEdgeInsetsZero;
        textView.textContainer.lineFragmentPadding = 0;
    
        // Setting height of textView to its contentSize.height
        CGRect textViewFrame = textView.frame;
        textViewFrame.size = textView.contentSize;
        textView.frame = textViewFrame;
    
        // Setting height of label accorting to it contents and width
        CGRect labelFrame = label.frame;
        labelFrame.size = [label sizeThatFits:CGSizeMake(width, HUGE_VALF)];
        labelFrame.size.width = width;
        label.frame = labelFrame;
    
        NSLog(@"Label bounds: %@", NSStringFromCGRect(label.bounds));
        NSLog(@"TextView bounds: %@", NSStringFromCGRect(textView.bounds));
    
        // Visualizing final effect with borders
        textView.layer.borderColor = [UIColor redColor].CGColor;
        textView.layer.borderWidth = 1.f;
        label.layer.borderColor = [UIColor greenColor].CGColor;
        label.layer.borderWidth = 1.f;
    }
    

    Console output:

    2016-09-01 14:29:06.118 stack39268477[943:243243] Label bounds: {{0, 0}, {100, 66}}
    2016-09-01 14:29:06.119 stack39268477[943:243243] TextView bounds: {{0, 0}, {100, 66}}
    

提交回复
热议问题