UITableView 헤더 섹션 사용자 정의
UITableView
각 섹션의 헤더 를 사용자 정의하고 싶습니다 . 지금까지 구현했습니다
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
이 UITabelViewDelegate
방법. 내가하고 싶은 것은 각 섹션에 대한 현재 헤더를 가져 와서 UILabel
하위보기로 추가 하는 것입니다.
지금까지는 그렇게 할 수 없습니다. 기본 섹션 헤더를 가져올 항목을 찾을 수 없기 때문입니다. 첫 번째 질문 은 기본 섹션 헤더를 얻는 방법이 있습니까?
가능하지 않으면 컨테이너 뷰를 만들어야 UIView
하지만 이번에는 기본 배경색, 그림자 색 등을 설정해야합니다. 섹션 헤더를주의 깊게 살펴보면 이미 사용자 정의되어 있기 때문입니다.
각 섹션 헤더에 대해 이러한 기본값을 어떻게 얻을 수 있습니까?
다들 감사 해요.
당신은 이것을 시도 할 수 있습니다 :
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 18)];
/* Create custom view to display section header... */
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, tableView.frame.size.width, 18)];
[label setFont:[UIFont boldSystemFontOfSize:12]];
NSString *string =[list objectAtIndex:section];
/* Section header is in 0th index... */
[label setText:string];
[view addSubview:label];
[view setBackgroundColor:[UIColor colorWithRed:166/255.0 green:177/255.0 blue:186/255.0 alpha:1.0]]; //your background color...
return view;
}
선택한 답변 tableView :viewForHeaderInSection:
이 정확합니다.
여기서 팁을 공유하십시오.
스토리 보드 / xib를 사용하는 경우 다른 프로토 타입 셀을 만들어 "섹션 셀"에 사용할 수 있습니다. 헤더를 구성하는 코드는 행 셀을 구성하는 방법과 유사합니다.
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
static NSString *HeaderCellIdentifier = @"Header";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:HeaderCellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:HeaderCellIdentifier];
}
// Configure the cell title etc
[self configureHeaderCell:cell inSection:section];
return cell;
}
Lochana Tejas 의 신속한 버전 :
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 18))
let label = UILabel(frame: CGRectMake(10, 5, tableView.frame.size.width, 18))
label.font = UIFont.systemFontOfSize(14)
label.text = list.objectAtIndex(indexPath.row) as! String
view.addSubview(label)
view.backgroundColor = UIColor.grayColor() // Set your background color
return view
}
기본 헤더보기를 사용하는 경우 기본 헤더보기 만 사용하여 텍스트를 변경할 수 있습니다
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
스위프트
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
보기를 사용자 정의하려면 새보기를 직접 작성해야합니다.
왜 UITableViewHeaderFooterView를 사용하지 않습니까?
headerInSection이 표시되지 않으면 시도해보십시오.
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 45;
}
주어진 섹션의 헤더 높이를 반환합니다.
이 시도......
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
{
// Background view is at index 0, content view at index 1
if let bgView = view.subviews[0] as? UIView
{
// do your stuff
}
view.layer.borderColor = UIColor.magentaColor().CGColor
view.layer.borderWidth = 1
}
lochana 및 estemendoza의 신속한 3 버전 답변 :
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let view = UIView(frame: CGRect(x:0, y:0, width:tableView.frame.size.width, height:18))
let label = UILabel(frame: CGRect(x:10, y:5, width:tableView.frame.size.width, height:18))
label.font = UIFont.systemFont(ofSize: 14)
label.text = "This is a test";
view.addSubview(label);
view.backgroundColor = UIColor.gray;
return view
}
또한 다음을 구현해야합니다.
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 100;
}
다른 답변은 기본 헤더보기를 다시 작성하는 것이 좋지만 실제로 주요 질문에 대답하지는 않습니다.
기본 섹션 헤더를 얻는 방법이 있습니까?
방법이 있습니다- tableView:willDisplayHeaderView:forSection:
대리인에게 구현 하십시오. 기본 헤더보기는 두 번째 매개 변수로 전달되며 여기에서이를 UITableViewHeaderFooterView
원하는대로 캐스트 한 다음 하위보기를 추가 / 변경할 수 있습니다.
오브제 C
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
// Do whatever with the header view... e.g.
// headerView.textLabel.textColor = [UIColor whiteColor]
}
빠른
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
{
let headerView = view as! UITableViewHeaderFooterView
// Do whatever with the header view... e.g.
// headerView.textLabel?.textColor = UIColor.white
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
//put your values, this is part of my code
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 30.0f)];
[view setBackgroundColor:[UIColor redColor]];
UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(20, 5, 150, 20)];
[lbl setFont:[UIFont systemFontOfSize:18]];
[lbl setTextColor:[UIColor blueColor]];
[view addSubview:lbl];
[lbl setText:[NSString stringWithFormat:@"Section: %ld",(long)section]];
return view;
}
이것이 가장 쉬운 해결책입니다. 다음 코드는 사용자 정의 섹션 헤더를 생성하는 데 직접 사용할 수 있습니다.
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
SectionHeaderTableViewCell *headerView = [tableView dequeueReusableCellWithIdentifier:@"sectionHeader"];
//For creating a drop menu of rows from the section
//==THIS IS JUST AN EXAMPLE. YOU CAN REMOVE THIS IF-ELSE.==
if (![self.sectionCollapsedArray[section] boolValue])
{
headerView.imageView.image = [UIImage imageNamed:@"up_icon"];
}
else
{
headerView.imageView.image = [UIImage imageNamed:@"drop_icon"];
}
//For button action inside the custom cell
headerView.dropButton.tag = section;
[headerView.dropButton addTarget:self action:@selector(sectionTapped:) forControlEvents:UIControlEventTouchUpInside];
//For removing long touch gestures.
for (UIGestureRecognizer *recognizer in headerView.contentView.gestureRecognizers)
{
[headerView.contentView removeGestureRecognizer:recognizer];
[headerView removeGestureRecognizer:recognizer];
}
return headerView.contentView;
}
참고 : SectionHeaderTableViewCell은 스토리 보드에서 작성된 사용자 정의 UITableViewCell입니다.
내가 당신이라면, NSString이 주어진 UIView를 반환하는 메소드를 만들 것입니다. 예를 들어
+ (UIView *) sectionViewWithTitle:(NSString *)title;
In the implementation of this method create a UIView, add a UILabel to it with the properties you want to set, and of course set its title to the given one.
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
if([view isKindOfClass:[UITableViewHeaderFooterView class]]){
UITableViewHeaderFooterView *headerView = view;
[[headerView textLabel] setTextColor:[UIColor colorWithHexString:@"666666"]];
[[headerView textLabel] setFont:[UIFont fontWithName:@"fontname" size:10]];
}
}
If you want to change the font of the textLabel in your section header you want to do it in willDisplayHeaderView. To set the text you can do it in viewForHeaderInSection or titleForHeaderInSection. Good luck!
Magically add Table View Header in swift
Recently I tried this.
I needed one and only one header in the whole UITableView.
Like I wanted a UIImageView on the top of the TableView. So I added a UIImageView on top of the UITableViewCell and automatically it was added as a tableViewHeader. Now I connect the ImageView to the ViewController and added the Image.
I was confused because I did something like this for the first time. So to clear my confusion open the xml format of the MainStoryBoard and found the Image View was added as a header.
It worked for me. Thanks xCode and swift.
@samwize's solution in Swift (so upvote him!). Brilliant using same recycling mechanism also for header/footer sections:
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let settingsHeaderSectionCell:SettingsHeaderSectionCell = self.dequeueReusableCell(withIdentifier: "SettingsHeaderSectionCell") as! SettingsHeaderSectionCell
return settingsHeaderSectionCell
}
call this delegate method
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return @"Some Title";
}
this will give a chance to automatically add a default header with dynamic title .
You may use reusable and customizable header / footer .
https://github.com/sourov2008/UITableViewCustomHeaderFooterSection
swif 4.2
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let header = view as? UITableViewHeaderFooterView else { return }
header.textLabel?.textAlignment = .center // for all sections
switch section {
case 1: //only section No.1
header.textLabel?.textColor = .black
case 3: //only section No.3
header.textLabel?.textColor = .red
default: //
header.textLabel?.textColor = .yellow
}
}
besides to titleForHeaderInSection, you can simply change view of header, footer. check my comment here: Change UITable section backgroundColor without loosing section Title
If you just want to add title to the tableView header dont add a view. In swift 3.x the code goes like this:
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
var lblStr = ""
if section == 0 {
lblStr = "Some String 1"
}
else if section == 1{
lblStr = "Some String 2"
}
else{
lblStr = "Some String 3"
}
return lblStr
}
You may implement an array to fetch the title for the headers.
Going back to the original question (4 years later), rather than rebuilding your own section header, iOS can simply call you (with willDisplayHeaderView:forSection:) right after it's built the default one. For example, I wanted to add a graph button on right edge of section header:
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
UITableViewHeaderFooterView * header = (UITableViewHeaderFooterView *) view;
if (header.contentView.subviews.count > 0) return; //in case of reuse
CGFloat rightEdge = CGRectGetMaxX(header.contentView.bounds);
UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(rightEdge - 44, 0, 44, CGRectGetMaxY(header.contentView.bounds))];
[button setBackgroundImage:[UIImage imageNamed:@"graphIcon"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(graphButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[view addSubview:button];
}
Use tableView: willDisplayHeaderView:
to customize the view when it is about to be displayed.
This gives you the advantage of being able to take the view that was already created for the header view and extend it, instead of having to recreate the whole header view yourself.
Here is an example that colors the header section based on a BOOL and adds a detail text element to the header.
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
// view.tintColor = [UIColor colorWithWhite:0.825 alpha:1.0]; // gray
// view.tintColor = [UIColor colorWithRed:0.825 green:0.725 blue:0.725 alpha:1.0]; // reddish
// view.tintColor = [UIColor colorWithRed:0.925 green:0.725 blue:0.725 alpha:1.0]; // pink
// Conditionally tint the header view
BOOL isMyThingOnOrOff = [self isMyThingOnOrOff];
if (isMyThingOnOrOff) {
view.tintColor = [UIColor colorWithRed:0.725 green:0.925 blue:0.725 alpha:1.0];
} else {
view.tintColor = [UIColor colorWithRed:0.925 green:0.725 blue:0.725 alpha:1.0];
}
/* Add a detail text label (which has its own view to the section header… */
CGFloat xOrigin = 100; // arbitrary
CGFloat hInset = 20;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(xOrigin + hInset, 5, tableView.frame.size.width - xOrigin - (hInset * 2), 22)];
label.textAlignment = NSTextAlignmentRight;
[label setFont:[UIFont fontWithName:@"Helvetica-Bold" size:14.0]
label.text = @"Hi. I'm the detail text";
[view addSubview:label];
}
참고URL : https://stackoverflow.com/questions/15611374/customize-uitableview-header-section
'IT story' 카테고리의 다른 글
Android Studio Gradle 아이콘 오류, 매니페스트 합병 (0) | 2020.06.21 |
---|---|
Linux 명령 출력에서 첫 번째 줄 생략 (0) | 2020.06.21 |
이미지를 Base64 문자열로 변환하는 방법은 무엇입니까? (0) | 2020.06.21 |
디렉토리를 반복적으로 반복하여 특정 확장자를 가진 파일을 삭제하는 방법 (0) | 2020.06.21 |
jQuery에서 입력 [유형 = 텍스트]의 값 변경 감지 (0) | 2020.06.21 |