You need to enable JavaScript to run this app. Objective-C 如何实现 UITableView 自定义Cell内UITextView的自动高度适配
优惠活动
大模型
产品
解决方案
定价
更多

Objective-C 如何实现 UITableView 自定义Cell内UITextView的自动高度适配

enter image description here

我需要为UITableView实现自定义Cell,但始终无法正确设置Cell内部两个UITextView的自动高度。以下尝试实现的代码无法达到预期效果:

@interface CreateFormViewController ()<UITableViewDelegate, UITableViewDataSource, UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableForm;

@end

@implementation CreateFormViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    MultipleChoiceTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MultipleChoiceTableViewCell class])];
    
    cell.viewMain.layer.cornerRadius = 20;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewAutomaticDimension;
}

- (void)textViewDidChange:(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;
}

@end

内容的提问来源于stack exchange,提问作者Oleg

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.18 04:54:04