Добавление iOS UITableView HeaderView (без заголовка раздела)
Я хочу добавить заголовок таблицы (не заголовки разделов), например, в приложении для контактов:
![enter image description here]()
точно так же - метка рядом с изображением выше таблицы.
Я хочу, чтобы все представления были прокручиваемыми, поэтому я не могу разместить их вне таблицы.
Как я могу это сделать?
Ответы
Ответ 1
UITableView
имеет свойство tableHeaderView
. Установите это для любого вида, который вы хотите там.
Используйте новый UIView
в качестве контейнера, добавьте текстовую метку и изображение к этому новому UIView
, затем установите tableHeaderView
в новое представление.
Например, в UITableViewController
:
-(void)viewDidLoad
{
// ...
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(XXX, YYY, XXX, YYY)];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(XXX, YYY, XXX, YYY)];
[headerView addSubview:imageView];
UILabel *labelView = [[UILabel alloc] initWithFrame:CGRectMake(XXX, YYY, XXX, YYY)];
[headerView addSubview:labelView];
self.tableView.tableHeaderView = headerView;
[imageView release];
[labelView release];
[headerView release];
// ...
}
Ответ 2
Вы можете сделать это довольно легко в Interface Builder. Просто создайте представление со столом и отбросьте другое представление на таблицу. Это станет представлением заголовка таблицы. Добавьте ярлыки и изображение к этому виду. См. Рис. Ниже для иерархии представления.
![View Hierarchy in Interface Builder]()
Ответ 3
Вы также можете просто создать ТОЛЬКО UIView в построителе интерфейса и перетащить ImageView и UILabel (чтобы он выглядел как ваш желаемый заголовок), а затем использовать его.
Как только ваш UIView будет выглядеть так, как вы этого хотите, вы можете программно инициализировать его из XIB и добавить в свой UITableView. Другими словами, вам не нужно создавать таблицу ENTIRE в IB. Просто headerView (таким образом, представление заголовка может быть повторно использовано и в других таблицах)
Например, у меня есть пользовательский UIView для одного из моих заголовков таблиц. Просмотр управляется xib файлом под названием "CustomHeaderView" и загружается в заголовок таблицы, используя следующий код в моем подклассе UITableViewController:
-(UIView *) customHeaderView {
if (!customHeaderView) {
[[NSBundle mainBundle] loadNibNamed:@"CustomHeaderView" owner:self options:nil];
}
return customHeaderView;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Set the CustomerHeaderView as the tables header view
self.tableView.tableHeaderView = self.customHeaderView;
}
Ответ 4
В Swift:
override func viewDidLoad() {
super.viewDidLoad()
// We set the table view header.
let cellTableViewHeader = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewHeaderCustomCellIdentifier) as! UITableViewCell
cellTableViewHeader.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewHeaderCustomCellIdentifier]!)
self.tableView.tableHeaderView = cellTableViewHeader
// We set the table view footer, just know that it will also remove extra cells from tableview.
let cellTableViewFooter = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewFooterCustomCellIdentifier) as! UITableViewCell
cellTableViewFooter.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewFooterCustomCellIdentifier]!)
self.tableView.tableFooterView = cellTableViewFooter
}
Ответ 5
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,tableView.frame.size.width,30)];
headerView.backgroundColor=[[UIColor redColor]colorWithAlphaComponent:0.5f];
headerView.layer.borderColor=[UIColor blackColor].CGColor;
headerView.layer.borderWidth=1.0f;
UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5,100,20)];
headerLabel.textAlignment = NSTextAlignmentRight;
headerLabel.text = @"LeadCode ";
//headerLabel.textColor=[UIColor whiteColor];
headerLabel.backgroundColor = [UIColor clearColor];
[headerView addSubview:headerLabel];
UILabel *headerLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(60, 0, headerView.frame.size.width-120.0, headerView.frame.size.height)];
headerLabel1.textAlignment = NSTextAlignmentRight;
headerLabel1.text = @"LeadName";
headerLabel.textColor=[UIColor whiteColor];
headerLabel1.backgroundColor = [UIColor clearColor];
[headerView addSubview:headerLabel1];
return headerView;
}