ios - UITableView框架基于单元格数

标签 ios iphone objective-c cocoa-touch uitableview

正如我的标题所说,我想根据单元格数设置UITableView的框架。单元格UITableView的高度是动态的,它不是固定的,为此我应用了以下逻辑

注意:我在UITableView上添加了UIScrollView,因此可以轻松滚动/查看整个表的内容。我知道UITableView具有自己的scrollView,但是在我的项目中,我需要根据单元格的数量(单元格的动态高度)设置UITableView的高度。

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self adjustHeightOfTableview]; // custom method for set height of tableView
}

- (void)adjustHeightOfTableview
{         
    CGRect frame = self.tblView.frame;
    frame.size.height = tblHeight; // tblHeight is CGFloat, declare in .h file
    self.tblView.frame = frame;
    self.scrollView.contentSize = CGSizeMake(300, self.tblView.frame.origin.y + self.tblView.frame.size.height);
}

并从
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%d", indexPath.row);

   NSString *AnswerHeight = [[self.listOfQuestions objectAtIndex:indexPath.row] objectForKey:@"Answer"]; // get 
    CGSize constraint = CGSizeMake(queWidth - (10.0f * 2), 20000.0f);
    CGSize size = [AnswerHeight sizeWithFont:[UIFont fontWithName:@"OpenSans-Bold" size:12] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];
    CGFloat height = MAX(size.height, 52);

    tblHeight = tblHeight + height + (10.0f * 2) - 1.5; // set tblHeight
    return height + (10.0f * 2) - 1.5;
}

但是问题是heightForRowAtIndexPath调用了2次,所以我无法获得正确的 tblHeight ,因此我的tableView的高度设置不正确。

为什么我的heightForRowAtIndexPath调用了2次,或者我该如何解决我的问题?或基于单元格的动态数量设置tableView的框架的任何其他解决方案?

只是为了理解
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

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

最佳答案

为什么不做空 footerView

UIView *footerView=[[UIView alloc]initWithFrame:CGRectZero];
self.taskListTable.tableFooterView=footerView;

然后在您认为会发生变化的地方更改表格框架:
例如viewWillApear或您的任何操作
self.taskListTable.frame= CGRectMake(0,0, 320, self.view.bounds.size.height);

关于ios - UITableView框架基于单元格数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20064879/

相关文章:

iphone - 如何阻止 NSNotification 中的观察者调用两次?

iphone - 您可以在不重新创建 IPA 的情况下将设备添加到临时分发吗?

iphone - 如果我不处理音频中断会怎样?

ios - 如何将全屏 subview 添加到 objective-c 中的当前 UIWindow 中,这将根据设备方向发生变化?

iphone - ASIFormDataRequest POST 错误 - iOS 6

ios - 在iOS 13之前的设备上返回的单元格的意外高度

ios - Watchkit 表行背景颜色以编程方式

ios - 将 UIButton 对齐到 UITableViewCell 的右侧

objective-c - 从 NSWindowsCP1252StringEncoding 文本创建文本

iphone - 为什么主队列上的 GCD dispatch_async 会导致后台队列死锁?