I try to implement a floating button over a UITableview
. So that when the content scrolls the button stay at the same position. The button shall hold a transparent image.
I did a smoketest and it worked fine with insertSubview:aboveSubview:
respectivly addSubView
But doing this on a UITableview
of an TableViewController
does not seem to work. The Button is on the tableView and scrolls with the tableView. Interestingly it scrolls as well under the header of the tableView...
How do I fix this - that the button is floating over the tableview?
TableViewController.m (updated with working code 12.07.2013)
Edit: Added a @property (nonatomic) float originalOrigin;
in TableViewController.h
- (void)viewDidLoad
{
[super viewDidLoad];
self.originalOrigin = 424.0;
[self addOverlayButton];
}
#pragma mark Camera Button
- (void)addOverlayButton {
// UIButton *oButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.oButton = [UIButton buttonWithType:UIButtonTypeCustom];
self.oButton.frame = CGRectMake(132.0, self.originalOrigin, 56.0, 56.0);
self.oButton.backgroundColor = [UIColor clearColor];
[self.oButton setImage:[UIImage imageNamed:@"CameraButton56x56.png"] forState:UIControlStateNormal];
[self.oButton addTarget:self action:@selector(toCameraView:) forControlEvents:UIControlEventTouchDown];
[self.view insertSubview:self.oButton aboveSubview:self.view];
}
// to make the button float over the tableView including tableHeader
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGRect tableBounds = self.tableView.bounds;
CGRect floatingButtonFrame = self.oButton.frame;
floatingButtonFrame.origin.y = self.originalOrigin + tableBounds.origin.y;
self.oButton.frame = floatingButtonFrame;
[self.view bringSubviewToFront:self.oButton]; // float over the tableHeader
}
You can implement the scrollViewDidScroll
delegate to change your floating button y origin while the user scroll the table, so that the button will float and stay at the same location.
There is a great example in WWDC 2011 session 125 that does exactly what you want.
In general, you need to save the original y origin of the button after you create it, or you can do it in viewDidLoad
, then implement the scrollViewDidScroll
and update the button frame.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGRect tableBounds = self.tableView.bounds;
CGRect floatingButtonFrame = self.floatingButton.frame;
floatingButtonFrame.origin.y = self.originalOrigin + tableBounds.origin.y;
self.floatingButton.frame = floatingButtonFrame;
}
来源:https://stackoverflow.com/questions/17593687/floating-uibutton-with-image-on-a-uitableview