ios 将 UIButton 添加到 UITableView 部分标题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20791577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding UIButton to UITableView section header
提问by Iowa15
I have a UITableView
with 1 section and for the section header, I would like to keep everything about the header the same but simply add a button on the right side. I cannot put the button in the navigation controller because the two available spots to put such a button are already occupied by other buttons.
我有UITableView
1 个部分,对于部分标题,我想保持标题的所有内容相同,但只需在右侧添加一个按钮。我无法将按钮放在导航控制器中,因为放置此类按钮的两个可用位置已被其他按钮占用。
Here you can see the result of what I tried to do. Now all I want to do is put an add button on the right side of the header, but what I have tried didn't work. I also tried some other solutions on StackOverflow, but they did not accomplish quite what I wanted to do. Additionally, if there is a better way of creating an add button, please let me know. I tried using a UIBarButtonItem
but I couldn't figure out how to add its view to an actual view. Thanks!
在这里你可以看到我尝试做的结果。现在我想要做的就是在标题的右侧放一个添加按钮,但是我尝试过的不起作用。我还在 StackOverflow 上尝试了其他一些解决方案,但它们并没有完成我想做的事情。此外,如果有更好的方法来创建添加按钮,请告诉我。我尝试使用 aUIBarButtonItem
但我无法弄清楚如何将其视图添加到实际视图中。谢谢!
This is what I have so far in my delegate:
这是我迄今为止在我的代表中所拥有的:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIButton *addButton = [[UIButton alloc] init]; //I also tried setting a frame for the
button, but that did not seem to work, so I figured I would just leave it blank for posting
the question.
addButton.titleLabel.text = @"+";
addButton.backgroundColor = [UIColor redColor];
[self.tableView.tableHeaderView insertSubview:addButton atIndex:0];
//I feel like this is a bad idea
return self.tableView.tableHeaderView;
}
- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 50;
}
回答by Yas T.
The problem is that your self.tableView.tableHeaderView
is nil
at this point in time, therefore you can't use it. So what you need to do is, create a UIView, add title, and button to it, style them, and return it.
问题是,你self.tableView.tableHeaderView
是nil
在这个时间点,所以你不能使用它。所以你需要做的是,创建一个 UIView,给它添加标题和按钮,给它们设置样式,然后返回它。
This should add a title and button to your section header, you still need to style the title with correct font and size but will give you an idea.
这应该为您的部分标题添加一个标题和按钮,您仍然需要使用正确的字体和大小设置标题的样式,但会给您一个想法。
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
CGRect frame = tableView.frame;
UIButton *addButton = [[UIButton alloc] initWithFrame:CGRectMake(frame.size.width-60, 10, 50, 30)];
[addButton setTitle:@"+" forState:UIControlStateNormal];
addButton.backgroundColor = [UIColor redColor];
UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 100, 30)];
title.text = @"Reminders";
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
[headerView addSubview:title];
[headerView addSubview:addButton];
return headerView;
}
回答by mwl
From iOS 6, you can also implement
从 iOS 6 开始,您还可以实现
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
in your UITableViewDelegate
. For example:
在您的UITableViewDelegate
. 例如:
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
if (section == 0) {
if ([view.subviews.lastObject isKindOfClass:[UIButton class]]) {
return;
}
UIButton *button = [UIButtonbuttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake(view.frame.size.width - 160.0, 0, 160.0, view.frame.size.height); // x,y,width,height
[button setTitle:@"My Button" forState:UIControlStateNormal];
[button addTarget:self action:@selector(sectionHeaderButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:button];
}
}
回答by Lubos
If you are interested in Swift solution:
如果您对 Swift 解决方案感兴趣:
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let frame = tableView.frame
let button = UIButton(frame: CGRectMake(5, 10, 15, 15)) // create button
button.tag = section
// the button is image - set image
button.setImage(UIImage(named: "remove_button"), forState: UIControlState.Normal) // assumes there is an image named "remove_button"
button.addTarget(self, action: #selector(TestController.remove(_:)), forControlEvents: .TouchUpInside) // add selector called by clicking on the button
let headerView = UIView(frame: CGRectMake(0, 0, frame.size.width, frame.size.height)) // create custom view
headerView.addSubview(button) // add the button to the view
return headerView
}
You might want to specify the height of the header in the section. This must be in sync with the height of the custom view:
您可能希望指定该部分中标题的高度。这必须与自定义视图的高度同步:
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return CGFloat(30)
}
回答by tiritea
You have 2 choices, both via your tableView.delegate
. The first involves implementing the delegate method
您有 2 个选择,都通过您的tableView.delegate
. 第一个涉及实现委托方法
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
which enables you to basically return anything you want in a custom view, which will be used as the header for your desired section. This could be as simple as
这使您基本上可以在自定义视图中返回您想要的任何内容,该视图将用作所需部分的标题。这可能很简单
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIButton *addButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
[addButton addTarget:self action:@selector(SomeMethod:) forControlEvents:UIControlEventTouchUpInside];
return addButton;
}
which will put a round info button (centered) as your header. But more likely you'll want to create an actual UIView object and populate it with your button (and a section title label?) and lay everything out as you like [see others' answers for how to do this].
这将放置一个圆形信息按钮(居中)作为您的标题。但更有可能的是,您想要创建一个实际的 UIView 对象并用您的按钮(和一个部分标题标签?)填充它,并根据需要布置所有内容[请参阅其他人的答案以了解如何执行此操作]。
However, the second approach is probably better for the general case of simply adding a button to (one of) your section headers [I know you stated 1 section, but a lot of folks will probably land on this question wanting to do similar in a multi-section table]. This involves implementing the delegate method
但是,第二种方法可能更适用于简单地向(其中一个)部分标题添加按钮的一般情况[我知道您说的是 1 个部分,但是很多人可能会在这个问题上做类似的事情多节表]。这涉及到实现委托方法
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
and basically adding your button to the header after-the-fact; specifically
并且基本上是事后将您的按钮添加到标题中;具体来说
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
// Remove old button from re-used header
if ([view.subviews.lastObject isKindOfClass:UIButton.class])
[view.subviews.lastObject removeFromSuperview];
if (section == MySectionNumberWithButton) {
UIButton *addButton = [UIButton buttonWithType:UIButtonTypeContactAdd];
[addButton addTarget:self action:@selector(SomeMethod:) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:addButton];
// Place button on far right margin of header
addButton.translatesAutoresizingMaskIntoConstraints = NO; // use autolayout constraints instead
[addButton.trailingAnchor constraintEqualToAnchor:view.layoutMarginsGuide.trailingAnchor].active = YES;
[addButton.bottomAnchor constraintEqualToAnchor:view.layoutMarginsGuide.bottomAnchor].active = YES;
}
}
Note, because the tableView re-uses headers, in a multi-section table you must make sure to remove any button you might have previously added, otherwise you'll eventually end up with buttons in unwanted sections. Then, if this is the right section, add the button to the existing header. Note, I'm using NSLayoutAnchor
(iOS 9+) to layout the button for brevity; you can do the same with NSLayoutConstraint
(iOS 6+)
请注意,由于 tableView 重复使用标题,因此在多节表中,您必须确保删除之前可能添加的任何按钮,否则最终会在不需要的部分中使用按钮。然后,如果这是正确的部分,则将该按钮添加到现有标题中。请注意,NSLayoutAnchor
为简洁起见,我使用(iOS 9+) 来布局按钮;你可以用NSLayoutConstraint
(iOS 6+)做同样的事情
This approach has the distinct advantage that - for just adding a button - you dont have to recreate the regular layout to match all your other (non-button) headers, or worry about margins changing when you rotate your device, etc. In particular, the header title is untouched and will retain any global appearance settings you may have defined for table headers (eg font, color, ...), all of which you'd have the messy job of re-creating if you took the tableView:viewForHeaderInSection:
approach.
这种方法具有明显的优势 - 只需添加一个按钮 - 您不必重新创建常规布局以匹配所有其他(非按钮)标题,也不必担心旋转设备时边距会发生变化等。特别是,标题标题保持不变,将保留您可能为表格标题定义的任何全局外观设置(例如字体、颜色等),如果您采用这种tableView:viewForHeaderInSection:
方法,您将不得不重新创建所有这些设置。
回答by Jiten Parmar
You can do that by using the below code, you can put any type of view in header view but you have to specify the frame for it.
你可以使用下面的代码来做到这一点,你可以在标题视图中放置任何类型的视图,但你必须为其指定框架。
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *view=[[UIView alloc]init];
UIButton *addButton=[UIButton buttonWithType:UIButtonTypeContactAdd];
addButton.frame=CGRectMake(250, 0, 100, 50);
[view addSubview:addButton];
[tblView.tableHeaderView insertSubview:view atIndex:0];
//I feel like this is a bad idea
return view;
}
回答by jbaraga
If you want to use Interface Builder to build your section header, you can use a UITableViewCell
as the header. Create a prototype cell for your header in your UITableView, customize as you would any other cell, including adding labels, buttons, and constraints.
如果要使用 Interface Builder 构建节标题,可以使用 aUITableViewCell
作为标题。在 UITableView 中为标题创建一个原型单元格,像任何其他单元格一样自定义,包括添加标签、按钮和约束。
You can instantiate in your UITableViewController lazily:
你可以懒惰地在 UITableViewController 中实例化:
lazy var headerCell: MyHeaderTableViewCell = {
let cell = tableView.dequeueReusableCell(withIdentifier: "Header") as! MyHeaderTableViewCell
return cell
}()
To make it the header:
使其成为标题:
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return headerCell
}
回答by Osman
Swift 4 :
斯威夫特 4:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let frame = tableView.frame
let button = UIButton(frame: CGRect(x: 5, y: 10, width: 15, height: 15))
button.tag = section
button.setImage(UIImage(named: "remove_button"), for: UIControl.State.normal)
button.addTarget(self,action:#selector(buttonClicked),for:.touchUpInside)
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height))
headerView.addSubview(button)
return headerView
}
This functions handles the button click:
这个函数处理按钮点击:
@objc func buttonClicked(sender:UIButton)
{
if(sender.tag == 1){
//Do something for tag 1
}
print("buttonClicked")
}