17

我将如何以编程方式添加此功能?我不确定我会搜索什么来找到这个。我知道如何添加 IBAction,但不知道生成图片中突出显示的此功能的代码。它是自定义单元格还是分隔符?

http://i40.tinypic.com/hthhdl.png

4

4 回答 4

33

这只是 TableView 中的一个标题,它们出现在您的部分顶部

如果您想要标题,请使用此方法:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

如果你想要一个自定义视图,或者这个:

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

对于高度:

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
于 2013-11-06T13:32:43.413 回答
25

试试这个以编程方式添加标题很容易..

UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(1, 50, 276, 30)];
headerView.backgroundColor = [UIColor colorWithRed:235/255.0f green:235/255.0f blue:235/255.0f alpha:1.0f];

UILabel *labelView = [[UILabel alloc] initWithFrame:CGRectMake(4, 5, 276, 24)];
labelView.text = @"hello";

[headerView addSubview:labelView];
self.tableView.tableHeaderView = headerView;

或者在 Swift 中尝试

var headerView: UIView = UIView.init(frame: CGRectMake(1, 50, 276, 30))
headerView.backgroundColor = UIColor(red: 235/255.0, green: 235/255.0, blue: 235/255.0, alpha: 1.0)

var labelView: UILabel = UILabel.init(frame: CGRectMake(4, 5, 276, 24))
labelView.text = "hello"

headerView.addSubview(labelView)
self.tableView.tableHeaderView = headerView

Swift 4.0 及更高版本

var headerView: UIView = UIView.init(frame: CGRect.init(x: 1, y: 50, width: 276, height: 30))
headerView.backgroundColor = UIColor(red: 235/255.0, green: 235/255.0, blue: 235/255.0, alpha: 1.0)

var labelView: UILabel = UILabel.init(frame: CGRect.init(x: 4, y: 5, width: 276, height: 24))
labelView.text = "hello"

headerView.addSubview(labelView)
self.tableView.tableHeaderView = headerView
于 2016-02-24T07:35:22.667 回答
14

为 Swift 4 更新

类似于 SimplePJ 的回答。如果你想为整个表视图创建一个自定义标题视图,你可以创建一个并将其设置为 tableHeaderView 像这样。

  let headerView: UIView = UIView.init(frame: CGRect(x: 1, y: 50, width: 276, height: 30))
  headerView.backgroundColor = .red

  let labelView: UILabel = UILabel.init(frame: CGRect(x: 4, y: 5, width: 276, height: 24))
  labelView.text = "My header view"

  headerView.addSubview(labelView)
  self.tableView.tableHeaderView = headerView

不要将这与创建表格视图部分标题混淆,您将在其中使用以下方法。

func headerView(forSection section: Int) -> UITableViewHeaderFooterView?

返回值是与section关联的标题视图,如果该部分没有标题视图,则返回 nil。

于 2017-12-20T17:02:35.023 回答
7

只需在 TableViewController 中实现这两个委托方法

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

在第一个方法中返回标题视图的高度,在第二个方法中返回应该显示的视图

这是一个例子

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 55.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"simpleHeader.png"]];
}
于 2013-11-06T13:42:33.313 回答