我很欣赏这是一个老问题。但是我找到了部分错误信息和不清楚的sn-ps的答案。所以对于它仍然有价值的东西,这就是我如何在UITableViewController 的视图底部添加一个“浮动”视图。是的,您可以这样做,即使接受的答案表明您不能这样做。
在您的-viewDidLoad 方法中,您可以创建一个我们将命名为bottomFloatingView 的视图。这也设置为属性。
请务必在表格视图的底部添加内容插入,这样可以避免浮动视图隐藏表格的任何内容。
接下来,您应该使用UIScrollViewDelegate 来更新浮动视图的框架。
错觉是您的视图被困在底部。实际上,此视图在您滚动时一直在移动,并且始终被计算为显示在底部。滚动视图非常强大!并且可能是我认为最被低估的 UIKit 类之一。
这是我的代码。注意属性、表格视图上的内容插入和-scrollViewDidScroll: 委托方法实现。我在情节提要中创建了浮动视图,这就是为什么您看不到正在设置的原因。
另外不要忘记,您可能还应该使用 KVO 来观察表格视图框架的变化。它可能会随着时间而改变,最简单的测试方法是在模拟器中打开和关闭通话状态栏。
最后一件事,如果您在表格视图中使用部分标题视图,这些视图将是表格视图中最顶部的视图,因此您还需要将浮动视图放在前面,当您改变它的框架。
@interface MyTableViewController ()
@property (strong, nonatomic) IBOutlet UIView *bottomFloatingView;
@end
@implementation MyTableViewController
static NSString *const cellIdentifier = @"MyTableViewCell";
- (void)dealloc
{
[self.tableView removeObserver:self forKeyPath:@"frame"];
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self.tableView addSubview:self.bottomFloatingView];
self.tableView.contentInset = UIEdgeInsetsMake(0.0, 0.0, CGRectGetHeight(self.bottomFloatingView.bounds), 0.0);
self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0.0, 0.0, CGRectGetHeight(self.bottomFloatingView.bounds), 0.0);
[self.tableView addObserver:self
forKeyPath:@"frame"
options:0
context:NULL];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 20;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
cell.textLabel.text = [NSString stringWithFormat:@"Row %d", indexPath.row];
return cell;
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
[self adjustFloatingViewFrame];
}
#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if([keyPath isEqualToString:@"frame"]) {
[self adjustFloatingViewFrame];
}
}
- (void)adjustFloatingViewFrame
{
CGRect newFrame = self.bottomFloatingView.frame;
newFrame.origin.x = 0;
newFrame.origin.y = self.tableView.contentOffset.y + CGRectGetHeight(self.tableView.bounds) - CGRectGetHeight(self.bottomFloatingView.bounds);
self.bottomFloatingView.frame = newFrame;
[self.tableView bringSubviewToFront:self.bottomFloatingView];
}
@end