Anchor a UIButton to the bottom of a UITableViewCo

2019-04-06 07:54发布

问题:

I have the following requirement. When a UITableViewController's view is displayed, there are a variable number of rows. Underneath the rows, a button should be displayed.

When the number of rows is small, the button should be anchored to the bottom of the view.

When the number of rows is larger, the delete button should be placed immediately after the last row.

In other words:

And not:

My best attempt at this so far has involved setting a tableFooterView and trying to update its height using the contentSize of the UITableView, but I am running into all sorts of problems. I might continue down this path and ask for some help, but first I want to know if anyone has alternative (better) solutions.

The result must play nicely with a double-sized status bar (during a call for example) and I am targeting iOS 6.0. I am not using interface builder.

回答1:

One possible solution to achieve this effect might have to use two different solutions.

  1. If the amount of rows means that the button will be off the screen then use the footerView like you have been doing.

  2. If the amount of rows means that the button will not be off screen then

    1. Add the button to the tableView
    2. Implement - (void)scrollViewDidScroll:(UIScrollView *)scrollView and update the frame of the button to be offset from the bottom.

The offset from the bottom might follow some logic like this

  1. yOffset = CGRectGetHeight(tableView.frame) - (CGRectGetHeight(button.frame) + somePadding)
  2. yOffset += tableView.contentOffset.y

This would mean that the button still moves up and down with the scrolling but you don't have to mess with the footerView height



回答2:

Keep both the table view and a button inside scroll view. Keep the button at the bottom of the scrollview. For proper scrolling to work you might want to set the scrollEnabled property of the scroll views. For more details on that check this up

Scrolling a UITableView inside a UIScrollView

EDIT:

yourView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin ;

Check the accepted answer for this question for more details on implimenting struts and springs using code: UIView autoresizingMask - Interface Builder to Code - Programmatically create struts and springs - Swift or Objective-C