floating UIButton with image on a UITableview [duplicate]

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-08 03:00:20

问题


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
}

回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!