固定在UITableview底部的一个浮动button与scrollViewDidScroll不能正常工作

我使用这段代码使UIButton在UITable的底部浮动,但最初UIButton会追加到UITableView的最后一个单元的下方,只有当我滚动页面的时候UIButton才会到达底部,一开始我会让button到底? 提前致谢!

- (void)scrollViewDidScroll:(UIScrollView *)scrollView { CGRect frame = self.chatButtonView.frame; frame.origin.y = scrollView.contentOffset.y + self.tableView.frame.size.height - self.chatButtonView.frame.size.height; self.chatButtonView.frame = frame; [self.view bringSubviewToFront:self.chatButtonView]; } 

在这里,我已经在tableview中添加了浮动button,同样可以添加任何其他控件。

 // Create button in `ViewDidLoad` and add to tableview. - (void)viewDidLoad { [super viewDidLoad]; // *** Creat a button, calculate Y position at bottom of table, assign frame & add to tableview *** _btnFloating = [UIButton buttonWithType:UIButtonTypeCustom]; CGFloat yPos = self.tableView.contentOffset.y + CGRectGetHeight(self.tableView.bounds) - CGRectGetHeight(_btnFloating.bounds); [_btnFloating setFrame:CGRectMake(0, yPos, [UIScreen mainScreen].bounds.size.width, 50)]; [self.tableView addSubview:_btnFloating]; // *** Adjust Inset and scroll indicator of tableview *** self.tableView.contentInset = UIEdgeInsetsMake(0.0f, 0.0f, CGRectGetHeight(_btnFloating.bounds), 0.0); self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0.0f, 0.0f, CGRectGetHeight(_btnFloating.bounds), 0.0); // *** Add observer on tableview frame change to update floating button frame *** [self.tableView addObserver:self forKeyPath:@"frame" options:0 context:NULL]; } #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 = _btnFloating.frame; newFrame.origin.x = 0; newFrame.origin.y = self.tableView.contentOffset.y + CGRectGetHeight(self.tableView.bounds) - CGRectGetHeight(_btnFloating.bounds); _btnFloating.frame = newFrame; [self.tableView bringSubviewToFront:_btnFloating]; } #pragma mark - UIScrollViewDelegate - (void)scrollViewDidScroll:(UIScrollView *)scrollView { [self adjustFloatingViewFrame]; } // Don't forget to remove Observer on Tableview otherwise it will lead to crash. -(void)dealloc { [self.tableView removeObserver:self forKeyPath:@"frame"]; } 

你可以做一些像,

  UIButton *chatBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)]; [chatBtn setTitle:@"Chat" forState:UIControlStateNormal]; [chatBtn setBackgroundColor:[UIColor lightGrayColor]]; [chatBtn addTarget:self action:@selector(chatbuttonClick) forControlEvents:UIControlEventTouchUpInside]; //chatbuttonClick is method that handle button's action self.myTableView.tableFooterView = chatBtn; 

scrollViewDidScroll不需要改变框架。 你必须设置tableFooterView而不是添加subview到它。

这个问题的另一个解决scheme是使用一个容器视图,可能更清晰的工作。