Reputation:
I have a UITextView in a (static) UITableviewCell. The textView is empty. What I want is the textView to resize dynamically. Meaning as the user enters some text inside, I want the textView to size to its content.
Next I want the cell to dynamically size to the textview's content.
I called textViewFitToContent in textView shouldChangeTextInRange.
My Problem is nothing works. I tried using just the textViewFitToContent in another project (without the uitableview) and it worked as expected.
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if (textView == myTextView)
{
if ([text isEqualToString:@"\n"])
{
[self insertXEveryNewLine:range :textView :@"\n\u2022 "];
return NO;
}
}
return YES;
}
- (BOOL)insertXEveryNewLine:(NSRange)place :(UITextView *)View :(NSString *)something
{
NSRange cursor = NSMakeRange(place.location + 3, 0);
NSMutableString *mutableT = [NSMutableString stringWithString:View.text];
[mutableT insertString:something atIndex:place.location];
[View setText:mutableT];
[View setSelectedRange:cursor];
[self textViewFitToContent:View];
return NO;
}
- (void)textViewFitToContent:(UITextView *)textView
{
CGFloat fixedWidth = textView.frame.size.width;
CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
CGRect newFrame = textView.frame;
newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
textView.frame = newFrame;
textView.scrollEnabled = NO;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UIFont *font = [UIFont systemFontOfSize:14.0f];
NSString *text = txtSymtoms.text;
CGFloat height = [text boundingRectWithSize:CGSizeMake(self.tableView.frame.size.width, 100) options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading) attributes:@{NSFontAttributeName: font} context:nil].size.height;
return height + 5;
}
I'm a begginer, so please don't be too harsh on me.
Thanx
Update
I deleted the heightForRowAtIndexPath because I have auto layout, and when I add a new line, nothing happens?
Upvotes: 1
Views: 256
Reputation: 7360
You need to calculate the UITableView's Cell height. Which would need to be base off the UitextViews height.
Upvotes: -1