iOS TextView在TableviewCell中自動增加高度
阿新 • • 發佈:2019-01-09
效果
設定Cell的AutoLayout
這裡要注意的是,添加了一個高度Constraint,這個Constraint是>=50的
SelfSizingCell.m
@interface SelfSizingCell ()<UITextViewDelegate> @property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightConstraint; @property (weak, nonatomic) IBOutlet UITextView *textview; @end @implementation SelfSizingCell - (void)awakeFromNib { // Initialization code self.textview.delegate = self; self.textview.scrollEnabled = false; } - (void)setSelected:(BOOL)selected animated:(BOOL)animated { [super setSelected:selected animated:animated]; // Configure the view for the selected state } -(void)textViewDidChange:(UITextView *)textView{ CGSize size = [textView sizeThatFits:CGSizeMake(CGRectGetWidth(self.frame), CGFLOAT_MAX)]; CGFloat height = size.height; if (height < 50) { self.heightConstraint.constant = 50; }else{ self.heightConstraint.constant = height; } [self.tableView beginUpdates]; [self.tableView endUpdates]; } @end
SelfSizingCell.h
@interface SelfSizingCell : UITableViewCell
@property (weak,nonatomic)UITableView * tableView;
@end
TableviewController
@implementation TableViewController - (void)viewDidLoad { [super viewDidLoad]; [self.tableView registerNib:[UINib nibWithNibName:@"SelfSizingCell" bundle:nil] forCellReuseIdentifier:@"cell"]; self.tableView.estimatedRowHeight = 50; self.tableView.rowHeight = UITableViewAutomaticDimension; self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero]; } #pragma mark - Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 1; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { SelfSizingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath]; cell.tableView = self.tableView; return cell; }