Oleg
Oleg

Reputation: 11

How to make auto height for these textview on objective-c

enter image description here

I want to make a custom cell for the table, but I just can't set the auto height for the two text views that are inside the cell

Code below doesn't work

@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

Upvotes: 0

Views: 47

Answers (1)

Oleg
Oleg

Reputation: 11

I changed the code in textViewDidChange to this one and it worked

[self.tableForm beginUpdates];
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;
[self.tableForm endUpdates];

Upvotes: 1

Related Questions