问题描述
我有一个基本的 UITableView,我在网上填写了一个 Web 服务,但是我找不到根据 textView 的高度设置单元格高度(动态单元格数)的方法.
这是我填充单元格的方式:
UITextView *textView = (UITextView *)[cell viewWithTag:106]; textView.text = [[stories objectAtIndex:indexPath.row] objectForKey:@"texte"];
在我的 cellForRow 方法中:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
我试过了,但得到 EXC_BAD_ACCESS
的错误- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PerleCell"]; UITextView *textView = (UITextView *)[cell viewWithTag:106]; textView.text = [[stories objectAtIndex:indexPath.row] objectForKey:@"texte"]; CGFloat *heightCell = (CGFloat*)textView.text.length; return *heightCell; }
推荐答案
在下面的方法中,你可以根据你的textView改变你的单元格的高度.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{ // Here check length of your textView // and after getting length return that length; NSString *myString = [[stories objectAtIndex:indexPath.row] objectForKey:@"texte"]; CGSize maximumSize = CGSizeMake(300, 9999); UIFont *myFont = [UIFont fontWithName:@"Helvetica" size:14]; CGSize myStringSize = [myString sizeWithFont:myFont constrainedToSize:maximumSize lineBreakMode:UILineBreakModeWordWrap]; return size.height; }
同样在 cellForRowAtIndexPath 方法中以相同的方式计算字符串的宽度,然后相应地给出 yourtextView 的宽度框架.之后在单元格的 contentView 上添加你的 textview.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ // Create cell here by using any style and for this you can google some what that how to create cell in UITableView // Here check length of your textView // and after getting length return that length; NSString *myString = [[stories objectAtIndex:indexPath.row] objectForKey:@"texte"]; CGSize maximumSize = CGSizeMake(300, 9999); UIFont *myFont = [UIFont fontWithName:@"Helvetica" size:14]; CGSize myStringSize = [myString sizeWithFont:myFont constrainedToSize:maximumSize lineBreakMode:UILineBreakModeWordWrap]; UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(0,0,300,size.height)]; textView.text = myString; [cell.contentView addSubView:textView]; return cell; }