문제

UitableView에서 섹션 헤더의 색상을 어떻게 변경하려면?

편집하다: DJ-S에서 제공 한 답변 iOS 6 이상을 고려해야합니다. 허용 된 답변은 구식입니다.

도움이 되었습니까?

해결책

바라건대이 방법은 UITableViewDelegate 프로토콜이 시작됩니다.

대상 C :

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{
  UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease];
  if (section == integerRepresentingYourSectionOfInterest)
     [headerView setBackgroundColor:[UIColor redColor]];
  else 
     [headerView setBackgroundColor:[UIColor clearColor]];
  return headerView;
}

빠른:

func tableView(_ tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView!
{
  let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 30))
  if (section == integerRepresentingYourSectionOfInterest) {
    headerView.backgroundColor = UIColor.redColor()
  } else {
    headerView.backgroundColor = UIColor.clearColor()
  }
  return headerView
}

업데이트 된 2017 :

스위프트 3 :

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
    {
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: 30))
        if (section == integerRepresentingYourSectionOfInterest) {
            headerView.backgroundColor = UIColor.red
        } else {
            headerView.backgroundColor = UIColor.clear
        }
        return headerView
    }

바꾸다 [UIColor redColor] 누구와도 UIColor 당신이 좋아. 차원을 조정할 수도 있습니다 headerView.

다른 팁

이것은 오래된 질문이지만 답을 업데이트해야한다고 생각합니다.

이 방법에는 고유 한 사용자 정의보기를 정의하고 생성하는 것이 포함되지 않습니다. iOS 6 이상에서는 다음을 정의하여 배경색과 텍스트 색상을 쉽게 변경할 수 있습니다.

-(void)tableView:(UITableView *)tableView 
    willDisplayHeaderView:(UIView *)view 
    forSection:(NSInteger)section

섹션 대의원 방법

예를 들어:

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    // Background color
    view.tintColor = [UIColor blackColor];

    // Text Color
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    [header.textLabel setTextColor:[UIColor whiteColor]];

    // Another way to set the background color
    // Note: does not preserve gradient effect of original header
    // header.contentView.backgroundColor = [UIColor blackColor];
}

여기에서 내 게시물에서 가져 왔습니다.https://happyteamlabs.com/blog/ios--to-customize-table-view-header-and-footer-colors/

스위프트 3 / 4

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
    view.tintColor = UIColor.red
    let header = view as! UITableViewHeaderFooterView
    header.textLabel?.textColor = UIColor.white
}

텍스트 색상을 변경하는 방법은 다음과 같습니다.

UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(10, 3, tableView.bounds.size.width - 10, 18)] autorelease];
label.text = @"Section Header Text Here";
label.textColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.75];
label.backgroundColor = [UIColor clearColor];
[headerView addSubview:label];

사용자 정의 색상으로 헤더를 원한다면 다음을 수행 할 수 있습니다.

[[UITableViewHeaderFooterView appearance] setTintColor:[UIColor redColor]];

이 솔루션은 iOS 6.0 이후로 잘 작동합니다.

다음 솔루션이 작동합니다 iOS 8+의 스위프트 1.2

override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {

    // This changes the header background
    view.tintColor = UIColor.blueColor()

    // Gets the header view as a UITableViewHeaderFooterView and changes the text colour
    var headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
    headerView.textLabel.textColor = UIColor.redColor()

}

대의원 에서이 코드를 추가하는 것을 잊지 마십시오. 그렇지 않으면 뷰/레이블의 높이와 관련하여 뷰가 차단되거나 경우에 따라 테이블 뒤에 나타납니다.

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

사용자 정의보기를 만들고 싶지 않다면 이와 같이 색상을 변경할 수도 있습니다 (iOS 6 필요).

-(void) tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
    if ([view isKindOfClass: [UITableViewHeaderFooterView class]]) {
        UITableViewHeaderFooterView* castView = (UITableViewHeaderFooterView*) view;
        UIView* content = castView.contentView;
        UIColor* color = [UIColor colorWithWhite:0.85 alpha:1.]; // substitute your color here
        content.backgroundColor = color;
    }
}

약 2 초 안에 main.storyboard에서 할 수 있습니다.

  1. 테이블 뷰를 선택하십시오
  2. 속성 검사관으로 이동하십시오
  3. 목록 항목
  4. 소스 헤드를 보려면 아래로 스크롤하십시오
  5. 배경을 바꾸다"

Have a look here

uitableviewheaderfooterview에서 배경색을 설정하는 것이 더 이상 사용되지 않았습니다. 이용 해주세요 contentView.backgroundColor 대신에.

섹션 영역의 배경과 텍스트 색상 설정 : (감사합니다. William Jockusch 그리고 Dj S)

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    if ([view isKindOfClass: [UITableViewHeaderFooterView class]]) {
        UITableViewHeaderFooterView* castView = (UITableViewHeaderFooterView*) view;
        castView.contentView.backgroundColor = [UIColor grayColor];
        [castView.textLabel setTextColor:[UIColor grayColor]];
    }
}

스위프트 4

변경하려면 배경색, 텍스트 레이블 색상 그리고 폰트 uitableview 섹션의 헤더 뷰는 간단히 재정의합니다. willDisplayHeaderView 처럼 테이블보기를 위해 :

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        let header = view as! UITableViewHeaderFooterView
        header.backgroundView?.backgroundColor = .white
        header.textLabel?.textColor = .black
        header.textLabel?.font = UIFont(name: "Helvetica-Bold", size: 14)
} 

이것은 나를 위해 완벽하게 작동했습니다. 그것이 당신도 당신을 도울 수 있기를 바랍니다!

헤더 뷰에서 이미지를 추가하는 방법은 다음과 같습니다.

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{
    UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)] autorelease];
    UIImageView *headerImage = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"top-gery-bar.png"]] autorelease];

    headerImage.frame = CGRectMake(0, 0, tableView.bounds.size.width, 30);

    [headerView addSubview:headerImage];

    return headerView;
}

iOS8 (베타) 및 Swift의 경우 원하는 RGB 색상을 선택하고 시도해보십시오.

override func tableView(tableView: UITableView!, viewForHeaderInSection section: Int) -> UIView! {
    var header :UITableViewHeaderFooterView = UITableViewHeaderFooterView()

    header.contentView.backgroundColor = UIColor(red: 254.0/255.0, green: 190.0/255.0, blue: 127.0/255.0, alpha: 1)
    return header

}

내 프로젝트에서 일반적인 UIViewController 대신 UitableViewController를 사용하고 있기 때문에 "재정의"가 있습니다. 그러나 섹션 헤더 색상을 변경하는 데 필수적이지 않습니다).

헤더의 텍스트는 여전히 보입니다. 섹션 헤더 높이를 조정해야합니다.

행운을 빕니다.

스위프트 2

블러 효과가 추가 된 상태에서 섹션 배경색을 성공적으로 변경할 수있었습니다 (정말 멋지다). 섹션의 배경색을 쉽게 변경하려면 :

  1. 먼저 스토리 보드로 이동하여 테이블 뷰를 선택하십시오
  2. 속성 검사관으로 이동하십시오
  3. 목록 항목
  4. 아래로 스크롤하십시오
  5. 배경을 바꾸다"

그런 다음 블러 효과를 위해 코드에 추가하십시오.

override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {

    // This is the blur effect

    let blurEffect = UIBlurEffect(style: .Light)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)

    // Gets the header view as a UITableViewHeaderFooterView and changes the text colour and adds above blur effect
    let headerView: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
    headerView.textLabel!.textColor = UIColor.darkGrayColor()
    headerView.textLabel!.font = UIFont(name: "HelveticaNeue-Light", size: 13)
    headerView.tintColor = .groupTableViewBackgroundColor()
    headerView.backgroundView = blurEffectView

}

신속하게 사용하면 다음을 사용하는 경우에 대답했습니다.

    override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let tableViewWidth = self.tableView.bounds

        let headerView = UIView(frame: CGRectMake(0, 0, tableViewWidth.size.width, self.tableView.sectionHeaderHeight))
        headerView.backgroundColor = UIColor.greenColor()

        return headerView
    }

iOS 8+

func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        tableView.tableHeaderView?.backgroundColor = UIColor.blue()
}

@DJ의 답변을 기반으로 Swift 3을 사용합니다. 이것은 iOS 10에서 훌륭하게 작동합니다.

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    // Background color
    view.tintColor = UIColor.black

    // Text Color
    let headerView = view as! UITableViewHeaderFooterView
    headerView.textLabel?.textColor = UIColor.white
}

iOS 7.X에서 정적 테이블보기 셀을 사용하는 프로젝트가 있습니다. WillDisplayHeaderView는 발사되지 않습니다. 그러나이 방법은 작동합니다.

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSLog(@"%s", __FUNCTION__);
    CGRect headerFrame = CGRectMake(x, y, w, h);    
    UIView *headerView = [[UIView alloc] initWithFrame:headerFrame];  
    headerView.backgroundColor = [UIColor blackColor];
 -(void) tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view
  forSection:(NSInteger)section
  {
        if ([view isKindOfClass: [UITableViewHeaderFooterView class]])
        {
             UITableViewHeaderFooterView *castView = (UITableViewHeaderFooterView *) view;
             UIView *content = castView.contentView;
             UIColor *color = [UIColor whiteColor]; // substitute your color here
             content.backgroundColor = color;
             [castView.textLabel setTextColor:[UIColor blackColor]];
        }
 }

이 코드가 그렇게 나쁘지 않다고 생각합니다.

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier(MyHeaderView.reuseIdentifier) as MyHeaderView
    let backgroundView = UIView()
    backgroundView.backgroundColor = UIColor.whiteColor()
    headerView.backgroundView = backgroundView
    headerView.textLabel.text = "hello"
    return headerView
}

iOS 7.0.4에서 자체 XIB로 사용자 정의 헤더를 만들었습니다. 여기에 언급 된 것은 없었습니다. UTIBLEVIEWHEADERFOOTERVIEW의 서브 클래스 여야했습니다. dequeueReusableHeaderFooterViewWithIdentifier: 그리고 배경색에 대해서는 수업이 매우 완고한 것 같습니다. 마지막으로 이름이 CustomBackGroudView가있는 UIView (코드 또는 IB로 수행 할 수 있음)를 추가 한 다음 BackgroundColor 속성을 설정했습니다. LayoutSubviews에서 : 해당보기의 프레임을 바운드로 설정했습니다. iOS 7과 함께 작동하며 결함이 없습니다.

// in MyTableHeaderView.xib drop an UIView at top of the first child of the owner
// first child becomes contentView

// in MyTableHeaderView.h
@property (nonatomic, weak) IBOutlet UIView * customBackgroundView;

// in MyTableHeaderView.m
-(void)layoutSubviews;
{
    [super layoutSubviews];

    self.customBackgroundView.frame = self.bounds;
}
// if you don't have XIB / use IB, put in the initializer:
-(id)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    ...
    UIView * customBackgroundView = [[UIView alloc] init];
    [self.contentView addSubview:customBackgroundView];
    _customBackgroundView = customBackgroundView;
    ...
}


// in MyTableViewController.m
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    MyTableHeaderView * header = [self.tableView
                                          dequeueReusableHeaderFooterViewWithIdentifier:@"MyTableHeaderView"];
    header.customBackgroundView.backgroundColor = [UIColor redColor];
    return header;
}

헤더 뷰의 레이어 색상을 변경하십시오.

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{
  UIView *headerView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0,    tableView.bounds.size.width, 30)] autorelease];
 headerView.layer.backgroundColor = [UIColor clearColor].CGColor
}

누구든지 신속한 사람이 있으면 제목을 유지합니다.

override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let view = UIView(frame: CGRect(x: 0,y: 0,width: self.tableView.frame.width, height: 30))
    view.backgroundColor = UIColor.redColor()
    let label = UILabel(frame: CGRect(x: 15,y: 5,width: 200,height: 25))
    label.text = self.tableView(tableView, titleForHeaderInSection: section)
    view.addSubview(label)
    return view
}

제 경우에는 다음과 같이 작동했습니다.

let headerIdentifier = "HeaderIdentifier"
let header = self.tableView.dequeueReusableHeaderFooterView(withIdentifier: headerIdentifier)
header.contentView.backgroundColor = UIColor.white

배경보기의 배경색을 설정하기 만하면됩니다.

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){         
  let tableHeader = view as! UITableViewHeaderFooterView        
  tableHeader.backgroundView?.backgroundColor = UIColor.white     
}

rubymotion / redpotion을 사용하면 이것을 탁자에 붙여 넣습니다.

  def tableView(_, willDisplayHeaderView: view, forSection: section)
    view.textLabel.textColor = rmq.color.your_text_color
    view.contentView.backgroundColor = rmq.color.your_background_color
  end

매력처럼 작동합니다!

콘솔 로그를 통해 Xcode에서 메시지를 받았습니다

TableView] UitableViewHeaderFootErview에서 배경색 설정이 더 이상 사용되지 않았습니다. 원하는 배경색을 가진 사용자 정의 UIVIEW를 대신 배경 뷰 속성에 설정하십시오.

그런 다음 새로운 uiview를 만들어 Headerview의 배경으로 놓습니다. 좋은 솔루션은 아니지만 Xcode가 말한 것처럼 쉽습니다.

하지만 func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) 다른 대의원 방법을 구현하지 않고도이를 달성 할 수 있습니다. 당신 안에 func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? 방법, 사용할 수 있습니다 view.contentView.backgroundColor = UIColor.white 대신에 view.backgroundView?.backgroundColor = UIColor.white 작동하지 않습니다. (나는 그것을 알고있다 backgroundView 선택 사항이지만 거기에있을 때에도 구현하지 않고는 흔들리지 않습니다. willDisplayHeaderView

UIAPPearance를 사용하면 다음과 같은 응용 프로그램의 모든 헤더에 대해 변경할 수 있습니다.

uitableViewHeaderFootERView.AppEarance (). BackgroundColor = 테마 .SubViewbackgroundColor

Swift 4는 매우 쉽게 만듭니다. 이것을 수업에 추가하고 필요에 따라 색상을 설정하십시오.

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        view.backgroundColor = UIColor(red: 0.094, green: 0.239, blue: 0.424, alpha: 1.0)
    }

또는 간단한 색상 인 경우

override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        view.backgroundColor = UIColor.white
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top