简体   繁体   English

调整UITextVIew和UITableViewCell的大小以适合内容

[英]Sizing UITextVIew and UITableViewCell to fit to Content

I have a UITextView in a (static) UITableviewCell. 我在(静态)UITableviewCell中有一个UITextView。 The textView is empty. textView为空。 What I want is the textView to resize dynamically. 我想要的是textView动态调整大小。 Meaning as the user enters some text inside, I want the textView to size to its content. 意思是当用户在其中输入一些文本时,我希望textView能够调整其内容的大小。

Next I want the cell to dynamically size to the textview's content. 接下来,我希望单元格动态调整为textview的内容大小。

I called textViewFitToContent in textView shouldChangeTextInRange. 我在textView shouldChangeTextInRange中称为textViewFitToContent。

My Problem is nothing works. 我的问题是没有任何效果。 I tried using just the textViewFitToContent in another project (without the uitableview) and it worked as expected. 我尝试在另一个项目中使用textViewFitToContent(没有uitableview),并且按预期工作。

- (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? 我删除了heightForRowAtIndexPath,因为我具有自动布局功能,当我添加新行时,什么也没发生?

You need to calculate the UITableView's Cell height. 您需要计算UITableView的单元格高度。 Which would need to be base off the UitextViews height. 这需要以UitextViews高度为基础。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM