Code Farmer Code Farmer - 3 months ago 75
iOS Question

A floating button fixed at the bottom of UITableview with scrollViewDidScroll not working properly

I am using this piece of code to make a UIButton floating fixed at
bottom of the UITable, but initially the UIButton will append exactly below
the last cell of the UITableView, only when I scroll the page the UIButton will
get to the bottom, what can I do to make the button come to the bottom at first?
Thanks in advance!

- (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];
}

Answer

Here, i have added floating button in tableview, same way you can add any other control.

// 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"];
}