Höhe einer UITextView an den Inhalt anpassen
Um die Höhe einer UITextView nachträglich an den Inhalt anzupassen, kann man folgenden Code verwenden.
1 2 3 4 5 6 7 8 9 10 11 12 13 | UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0.0, 0.0, 280.0, 0.0)]; UIFont *textViewFont = [UIFont fontWithName:@"Helvetica" size:16.0]; [self.view addSubview:textView]; textView.font = textViewFont; textView.textColor = [UIColor blackColor]; textView.userInteractionEnabled = NO; textView.text = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n\nQuisque posuere lobortis augue, ut dapibus massa consectetur non.\nUt cursus ante eu ante laoreet bibendum.\n\nNullam a nibh id nisl tempus suscipit facilisis quis lectus?"; CGRect frame = textView.frame; frame.size.height = textView.contentSize.height; textView.frame = frame; |
Wichtig ist dabei die Reihenfolge. Die contentSize wird erst durch das Hinzufügen der textView als Subview einer anderen View gesetzt. Davor entspricht sie der frame.size. Also in diesem Fall wäre die Höhe 0.