陈斌彬的技术博客

Stay foolish,stay hungry

iOS中tableview中headerview总保持在屏幕上方和随着屏幕滑动一起移动至消失

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
    headView.backgroundColor = [UIColor redColor];

    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width / 3, 30)];
    nameLabel.text = @"名称代码";
    nameLabel.textAlignment = NSTextAlignmentCenter;
    nameLabel.textColor = [UIColor whiteColor];
    nameLabel.font = [UIFont boldSystemFontOfSize:15.0];

    UILabel *priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 3, 0, self.view.frame.size.width / 3, 30)];
    priceLabel.text = @"最新价";
    priceLabel.textAlignment = NSTextAlignmentCenter;
    priceLabel.textColor = [UIColor whiteColor];
    priceLabel.font = [UIFont boldSystemFontOfSize:15.0];

    UILabel *precentLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 3 * 2, 0, self.view.frame.size.width / 3, 30)];
    precentLabel.text = [_titleStr substringToIndex:2];
    precentLabel.textAlignment = NSTextAlignmentCenter;
    precentLabel.textColor = [UIColor whiteColor];
    precentLabel.font = [UIFont boldSystemFontOfSize:15.0];

    [headView addSubview:nameLabel];
    [headView addSubview:priceLabel];
    [headView addSubview:precentLabel];

    return headView;
}

2 : 想随着屏幕滑动一起移动至消失的话: 就直接调用属性方法,将创建的view指定到headerview的试图()

例子: {在viewdidload中}
self.headerView = [[HeaderView alloc] initWithFrame:CGRectMake(0, 0, 320, 150)];
self.tableView.tableHeaderView = self.headerView;

Resource Reference