如何将静态 UIButton 覆盖在 UITableView 上

Posted

技术标签:

【中文标题】如何将静态 UIButton 覆盖在 UITableView 上【英文标题】:How to Put a static UIButton Overlaying a UITableView 【发布时间】:2015-04-07 04:24:47 【问题描述】:

基本上,无论表格视图是否滚动,我都想在顶部创建一个静态 UIButton。但是,我尝试将 UIButton 添加为 UIView 的子视图,并使用“bringSubviewToFront”方法将其置于顶部。但是,当我滚动 UITableView 时,UIButton 仍然会移动。因此,如何制作一个覆盖 UITableView 的静态 UIButton?

这是我的代码:

#import "DiscoverTimelineTableViewController.h"

@interface DiscoverTimelineTableViewController ()

@property (strong, nonatomic) UIView* myview;

@end

@implementation DiscoverTimelineTableViewController

- (void)viewDidLoad 
    [super viewDidLoad];

    [self displayMakePlanButton];

    NSLog(@"%f", self.view.layer.zPosition);
    NSLog(@"%f", self.tableView.layer.zPosition);


- (void)didReceiveMemoryWarning 
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;


- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

    return 100.0f;



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    // Configure the cell...
    cell.textLabel.text = @"Sleepy";

    return cell;


#pragma mark - Add the make plan button
- (void) displayMakePlanButton

    CGFloat buttonWidth = self.view.frame.size.width;
    CGFloat buttonHeight = 104.0f;

    CGFloat navBarHeight = self.navigationController.navigationBar.frame.size.height;
    CGFloat statBarHeight = [UIApplication sharedApplication].statusBarFrame.size.height;

    UIButton *makePlanButton = [UIButton buttonWithType: UIButtonTypeCustom];
    [makePlanButton setFrame:CGRectMake(0, self.view.frame.size.height - buttonHeight - navBarHeight - statBarHeight, buttonWidth, buttonHeight)];

    [makePlanButton setBackgroundColor:[UIColor colorWithRed:0.286 green:0.678 blue:0.231 alpha:1]];
    [makePlanButton setTitle:@"MAKE PLAN" forState:UIControlStateNormal];

    [self.view addSubview:makePlanButton];
    //makePlanButton.layer.zPosition = 1;
    [self.view bringSubviewToFront:makePlanButton];
    NSLog(@"%f", makePlanButton.layer.zPosition);


@end

【问题讨论】:

【参考方案1】:

您正在使用表格视图控制器,因此 self.view 是表格视图。表格视图是滚动视图,因此视图与其他所有内容一起滚动。

您应该使用带有表作为子视图的常规视图控制器。

或者,您可以尝试在 scrollViewDidScroll: 滚动视图委托方法中重置视图的框架,但我认为视图仍然会有点抖动。

最后,您可以将按钮直接添加到UIWindow,但这可能会带来一系列其他旋转、动画和过渡问题。

【讨论】:

以上是关于如何将静态 UIButton 覆盖在 UITableView 上的主要内容,如果未能解决你的问题,请参考以下文章

将静态 UIButton 覆盖到 UICollectionView

如何覆盖 Xamarin.IOS UIButton 的 LayoutSublayersOfLayer 行为?

如何在 UIButton 子类中覆盖 -drawrect?

避免 UIPickerView ios 上的 UIButton 覆盖

在 iOS 的 UITableViewCell 中更新 UIButton 图像时发生冲突

如何使自定义 UIButton 变暗