0

我以编程方式向 UITableViewController 添加一个按钮,如下所示:

-(void)createFlipButton
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeInfoDark];
    button.frame = CGRectMake(282, 372, 18, 19);
    [button addTarget:self action:@selector(flipView) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:button];
    [self.view bringSubviewToFront:button];
}

但它卡在占据 button.frame 空间的单元格中。为什么不 [self.view bringSubviewToFront:button]工作?

此外, [self.tableView bringSubviewToFront:button]也不起作用。

4

5 回答 5

1

你真正想要的是一个浮动视图,即当表格视图滚动时不会移动的视图。按钮看起来粘在您的单元格上的原因是整个表格处于滚动视图中,因此当内容移动时,按钮也会移动。

方法是在表格滚动时调整添加视图的位置。只需实现委托方法:

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
     CGPoint buttonOrigin = CGPointMake(200,50);
     self.button.frame = CGRectMake(buttonOrigin.x, buttonOrigin.y + self.tableView.bounds.origin.y, self.button.frame.size.width, self.button.frame.size.height);
}

您需要为您的按钮存储一个引用,以便您可以在此处访问它,并且可能还将按钮的位置放入 ivar。

如果您可以访问 WWDC 2011 视频,您会在 Session 125 中找到诀窍。

于 2012-09-30T16:15:34.937 回答
0

你可以创建一个透明的 UIView;将您的按钮添加到该 UIView,然后将该 UIView 添加到您拥有的视图层次结构中。这应该按照您的要求工作(按钮不是表格视图的一部分)。如果需要有关示例代码的任何帮助,请在下方发表评论。

于 2012-09-25T19:31:43.487 回答
0

每当我想在同一个视图中使用表格视图和其他 UI 项时,我都会使用 UIViewController。这个视图控制器符合 UITableViewDelegate 和 UITableViewDataSource。UITableView 委托和 DataSource 方法已实现,因此该视图控制器也可用作表视图控制器。我使用 IB 或故事板来建立联系。但是,如果您想以编程方式创建所有内容,这也应该有效。

在您的情况下,如果您希望 UIButton 与表格视图分开,则使用上述 UIViewController 是选项之一。

于 2012-09-26T11:29:56.630 回答
-1

您应该在 tableHeaderView 中添加按钮

-(void)createFlipButton
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeInfoDark];
    button.frame = CGRectMake(10, 10, 18, 19);
    [button addTarget:self action:@selector(flipView) forControlEvents:UIControlEventTouchDown];
    self.tableView.tableHeaderView = button
    self.tableView.delegate = self;
    [self.tableView reloadData];
}



and implement the following UITableView Delegate
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section   {

return 44;/// sample
}
于 2012-09-17T13:57:43.350 回答
-1

UItableViewCell上添加按钮

[cell.contentView addSubview:Button];
于 2012-10-01T11:10:01.633 回答