iOS TextView在TableviewCell中自动增加高度

自适应TableViewCell高度
本文介绍了一种使用AutoLayout实现自适应高度的UITableViewCell方法。通过设置一个最小高度约束,并监听UITextView内容变化来调整Cell的高度。

原创Blog,转载请注明出处
http://blog.youkuaiyun.com/hello_hwc?viewmode=list
我的stackoverflow

profile for Leo on Stack Exchange, a network of free, community-driven Q&A sites


前言:来自自己的一个StackOverFlow答案


效果


设置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;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值