以编程方式向UITableview添加标头
如何以编程方式添加此function? 我不确定我会搜索到什么。 我知道如何添加IBAction而不是代码来生成图片中突出显示的此function。 它是自定义单元格还是分隔符?
这只是TableView中的标题,它们出现在您的部分之上
如果您想要标题,请使用此方法:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
或者如果你想要一个自定义视图这个:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
并为高度:
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
试试这个以编程方式添加标题很容易..
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]; .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
只需在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"]]; }
更新了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?
返回值是与节相关联的标题视图,如果该节没有标题视图,则返回nil。