2016-09-01 3 views
3

Я использую приведенный ниже код для вычисления высоты текста, а затем установить эту высоту для UILabel и UITextViewКак рассчитать высоту основания TextView по тексту

CGSize targetSize = CGSizeMake(300, CGFLOAT_MAX); 
NSString *message = @"The Internet connection appears to be offline."; 

NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init]; 
CGSize boundingBox = [message boundingRectWithSize:targetSize 
               options:NSStringDrawingUsesLineFragmentOrigin 
              attributes:@{NSFontAttributeName:FontOpenSanWithSize(14)} 
               context:context].size; 

CGSize size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height)); 
// it will return size:width = 299 and size height 20 
// => if I use this height and set for UILabel, it can display full content 
// => if I use this height and set for UITextView, it can not display full content 

Это работа идеально подходит для UILabel но UITextView когда-то вычислить неправильно.
Я думаю, проблема возникла из-за того, что заполнение (слева, справа) UITextView больше, чем UILabel.
Так как я могу рассчитать правильный размер текста для отображения в UITextView. Любая помощь или предложение были бы очень оценены.

как описание изображения ниже
С того же размера (300), тем же шрифтом, текст же, но UITextView дисплей в 2-х линий, но UILabel в 1 линии. И мой код высоты высчитывает возврата 20, не достаточно для отображения в 2-х линий, поэтому UITextView не может отображать полное содержание

Причина, почему мне нужно рассчитать высоту UITextView базы по тексту, потому что мой UITextView находится в всплывающем окне. И всплывающий высота будет зависеть от высоты TextView

enter image description here

+0

вы можете связать постоянную высоту текста, а затем использовать ее для обновления высоты. Я думаю, –

+0

Просто зайдите сюда http://stackoverflow.com/questions/31678779/how-to-dynamically-change-the-textview-height-and- cell-height-to-the-t –

+0

Возможный дубликат [Как настроить UITextView для его содержимого?] (http://stackoverflow.com/questions/50467/how-do-i-size-a- uitextview-to-its-content) – Sandy

ответ

3

Вам не нужно вычислять Высота UITextview по тексту.

Просто измените рамку и установить высоту, как это:

textview.size.height = textview.contentSize.height; 

Это простое решение. Я надеюсь, это поможет вам.

+0

мой случай отличается, поэтому я не могу использовать сюда. проверьте мое обновление –

6

Есть две вещи, которые вы можете попробовать:

  1. Набор textView.textContainerInset = UIEdgeInsetsZero
  2. Набор textView.textContainer.lineFragmentPadding = 0

С помощью этих операций вы можете избавиться от всех накладку в TextView и когда его ширина спичек с меткой одна высота тоже одна и та же.

Вот пример кода, вы можете поместить в пустой ViewController и проверить это сами:

- (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; 
} 

Консоль вывода:

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}} 
+0

TextView.textContainer.lineFragmentPadding сделал трюк ... – TheEye

0

Это вычисляет размер любой строки, расфасованные или не расфасованные вы их в текстовом виде.

let frame = NSString(string: yourText).boundingRect(
    with: CGSize(width: yourDesiredWidth, height: .infinity), 
    options: [.usesFontLeading, .usesLineFragmentOrigin], 
    attributes: [.font : yourFont], 
    context: nil) 

let height = frame.size.height 
0

self.textView.textContainerInset = UIEdgeInsets.zero self.textView.textContainer.lineFragmentPadding = 0

В раскадровке или XIB марки TextView высота> = 0.

Если вы используете текстовое представление с табличным представлением. Рассчитайте высоту ячейки в соответствии с содержимым, textview отрегулирует ее пространство.

Смежные вопросы