Ios 我可以实时更改UITableViewCell的高度吗?

Ios 我可以实时更改UITableViewCell的高度吗?,ios,swift,tableview,Ios,Swift,Tableview,我有一个UITableViewCell,在这个单元格的内部有一个UITextView。我何时更改UITextView的文本我想实时更改单元格高度 我该怎么做?谢谢。如果您使用自动布局来计算单元格高度,我认为您只需在tableView上使用reloadData()方法。您需要根据以下链接设置UITableviewCell的自动布局: 在此之后,您必须根据需要使用以下链接重新加载UITableViewCell: 参考来源: 在自动布局完成后,您需要计算单元格的高度。我的意思是,在根据提供的文本排列

我有一个
UITableViewCell
,在这个单元格的内部有一个
UITextView
。我何时更改
UITextView的文本
我想实时更改单元格高度


我该怎么做?谢谢。

如果您使用自动布局来计算单元格高度,我认为您只需在tableView上使用
reloadData()
方法。

您需要根据以下链接设置
UITableviewCell
的自动布局:

在此之后,您必须根据需要使用以下链接重新加载
UITableViewCell

参考来源:

在自动布局完成后,您需要计算单元格的高度。我的意思是,在根据提供的文本排列内部视图的宽度/高度之后

遵循解决方案:

首先在视图控制器下面添加
UITableView
委托方法

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}
heightForRowAtIndexPath:
delegate方法中计算单元格高度:

*这很重要*:请记住,分配单元格标签和文本视图的值与在
cellforrowatinexpath
delegate方法中所做的相同

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
 NSString *cellIdentifier = [NSString stringWithFormat:@"CustomCell%d%d",(int)indexPath.section, (int)indexPath.row];

    CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }

    // Set cell label text same like you did in `cellForRowAtIndexPath`
    // For example
    NSString *name = [self.dataArray objectAtIndex:indexPath.row];
    cell.nameLabel.text = name;
    cell.textView.text = @"This is long text.....";

    [cell setNeedsUpdateConstraints];
    [cell updateConstraintsIfNeeded];
    cell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(tableView.bounds), CGRectGetHeight(cell.bounds));

    [cell setNeedsLayout];
    [cell layoutIfNeeded];

    CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    height += 5;

    return height;
}
现在,如果您已经创建了
CustomCell
,请在cell的
initWithStyle:
方法中添加以下约束

// Other controls initialisation and creation code
// ....
// TextView control setup

[self.textView setTranslatesAutoresizingMaskIntoConstraints:NO];
// Above line is very important otherwise below constraint wont work
// Because by default it uses auto size constraints


// Other controls constraints
// ....

[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[textView]-10-|" options:0 metrics:nil views:@{@"textView" : self.textView}]];

NSLayoutConstraint *pinToBottom = [NSLayoutConstraint constraintWithItem:self.textView
                                                               attribute:NSLayoutAttributeBottom
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self.contentView
                                                               attribute:NSLayoutAttributeBottom
                                                              multiplier:1
                                                                constant:0];
[self.contentView addConstraint:pinToBottom];
并在下面添加委托方法

- (void)layoutSubviews {
    [super layoutSubviews];

    [self.contentView setNeedsLayout];
    [self.contentView layoutIfNeeded];

    self.textView.preferredMaxLayoutWidth = CGRectGetWidth(self.textView.frame);
}
但如果您尚未创建自定义单元,并且正在使用故事板中的单元,请将底部约束添加到superView(单元的内容视图)


此解决方案的主要思想是计算textView的高度并将其指定给行

注意:这是Swift 3代码:

class ViewController: UIViewController {

    // array containing rows heights:
    var rowHeights = [CGFloat]()

    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()

        // fill it with default values of row heights
        for _ in 1...10 {
            rowHeights.append(44)
        }
    }
}

extension ViewController: UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return rowHeights[indexPath.row]
    }


    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // return the actual number of your rows...
        return 10
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TextViewTableViewCell") as! TextViewTableViewCell

        // assgin the tag of current text view to use for determining the current cell's height
        cell.textView.tag = indexPath.row

        cell.textView.delegate = self

        return cell
    }
}

extension ViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {

        // calculate the current height and append it in the rowHeights depends on the textView's tag. Add your the textView fontSize instead of 15
        rowHeights[textView.tag] = (textView.text?.heightWithConstrainedWidth(width: tableView.frame.size.width, font: UIFont.systemFont(ofSize: 15)))!

        // for updating the tableView appearence (don't use "reloadData", it will resignFirstResponder the textView)
        tableView.beginUpdates()
        tableView.endUpdates()

        textView.setContentOffset(CGPoint.zero, animated: true)

        //textView.becomeFirstResponder()
    }
}

extension String {
    // this method calculates the height of string depending on your view width and font
    func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

        return boundingBox.height
    }
}
CustomTableViewCell:

class TextViewTableViewCell: UITableViewCell {
    @IBOutlet weak var textView: UITextView!
}
输出应如下所示:

希望这有帮助

从cellForRowAtIndexPath委托调用此方法

此方法将显示单元格的高度

在cellForRowAtIndexPath中使用此语句


您需要自动调整单元格大小。看看这个教程不,我知道这个技巧。设置表视图后,我尝试更改表视图单元格。您是否可以发布您迄今为止尝试过的任何内容的代码?@Zhandos.Nurakhmetov您是否尝试过
UITableViewAutomaticDimension
???是的,我使用了autodimension
(CGSize)attributedText:(NSAttributedString *)text sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size 
{
        return  [self textViewHeightForAttributedText:text constrainedToSize:size];
}
(CGSize)textViewHeightForAttributedText: (NSAttributedString*)text constrainedToSize:(CGSize)size 
   {
        UITextView *calculationView = [[UITextView alloc] init];
        [calculationView setAttributedText:text];
        CGSize size1 = [calculationView sizeThatFits:size];
        return size1;
   }
CGSize  textSize = {tableView.frame.size.width-70, 10000.0 };
CGSize size1 =[self attributedText:attrString sizeWithFont:[UIFont fontWithName:@"HelveticaNeue-Light" size:14] constrainedToSize:textSize];