UITableViewHeaderFooterView : 배경색을 변경할 수 없습니다.


124

UITableViewHeaderFooterView의 배경색을 변경하려고합니다. 보기가 표시 되더라도 배경색은 기본 색상으로 유지됩니다. xcode에서 다음과 같은 로그를 받고 있습니다.

UITableViewHeaderFooterView의 배경색 설정은 더 이상 사용되지 않습니다. 대신 contentView.backgroundColor를 사용하세요.

그러나 다음 옵션은 작동하지 않습니다.

myTableViewHeaderFooterView.contentView.backgroundColor = [UIColor blackColor];
myTableViewHeaderFooterView.backgroundView.backgroundColor = [UIColor blackColor];
myTableViewHeaderFooterView.backgroundColor = [UIColor blackColor];

또한 xib 파일에서보기의 배경색을 변경해 보았습니다.

어떤 제안? 감사.


2
iOS 13에서는 contentView.backgroundColor를 사용하십시오. 나는이 애플을 생각 업데이트
— TA Truhoada

답변:


94

myTableViewHeaderFooterView.tintColor를 사용하거나 myTableViewHeaderFooterView.backgroundView에 사용자 지정 배경보기를 할당해야합니다.


2
myTableViewHeaderFooterView.tintColor는 완벽하게 작동합니다. 답변 해주셔서 감사합니다!
— Chun

15
이유는 모르지만 tintColoriOS7에서 작업하지 않습니다. 사용자 지정보기를 지정해야만 색상을 변경할 수 있습니다.myTableViewHeaderFooterView.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"myImage.png"]];
— skywinder 2014 년

7
TintColor는 배경색이 아닙니다 !!
— João Nunes

189

iOS 8, 9, 10, 11 ...

모든 색상 (알파 포함)을 설정하는 유일한 방법은 다음을 사용하는 것입니다 backgroundView.

빠른

self.backgroundView = UIView(frame: self.bounds)
self.backgroundView.backgroundColor = UIColor(white: 0.5, alpha: 0.5)

Obj-C

self.backgroundView = ({
    UIView * view = [[UIView alloc] initWithFrame:self.bounds];
    view.backgroundColor = [UIColor colorWithWhite: 0.5 alpha:0.5];
    view;
    });

댓글에 대한 응답

  • 이러한 다른 옵션 중 어느 것도 안정적으로 작동하지 않습니다 (아래 설명에도 불구하고).

    // self.contentView.backgroundColor = [UIColor clearColor];
    // self.backgroundColor = [UIColor clearColor];
    // self.tintColor = [UIColor clearColor];
  • 는 backgroundView자동으로 크기가 조정됩니다. (제약 조건 추가 필요 없음)

  • UIColor(white: 0.5, alpha: 0.5)또는로 알파를 제어합니다 backgroundView.alpha = 0.5.
    (물론 어떤 색이든 상관 없습니다)

  • XIB 를 사용할 때 루트 뷰를UITableViewHeaderFooterView 하고 연결 backgroundView프로그램을 :

    등록 :

    tableView.register(UINib(nibName: "View", bundle: nil),
                       forHeaderFooterViewReuseIdentifier: "header")

    로드 :

    override func tableView(_ tableView: UITableView,
                            viewForHeaderInSection section: Int) -> UIView? {
        if let header =
            tableView.dequeueReusableHeaderFooterView(withIdentifier: "header") {
            let backgroundView = UIView(frame: header.bounds)
            backgroundView.backgroundColor = UIColor(white: 0.5, alpha: 0.5)
            header.backgroundView = backgroundView
            return header
        }
        return nil
    }

데모

↻ 애니메이션 재생

► GitHub 에서이 솔루션을 찾고 Swift Recipes 에 대한 추가 세부 사항을 찾으십시오 .


5
그 이유는 contentView가 존재하지 않습니다. tintcolor는 뷰의 배경이 아닌 색조를 지정하는 것입니다. backgroundcolor는 더 이상 사용되지 않습니다. 따라서 당신의 방식은 그것을 작동시키는 방법입니다. Btw 멋진 코드 구문
— João Nunes 2014 년

@ JoãoNunes, C # / Xamarin을 사용하면 구문이 더 view.BackgroundView = new UIView(view.Bounds) { BackgroundColor = UIColor.Clear };
— 깔끔해집니다

: 엑스 코드 6.1.1에서는 런타임 콘솔 경고를 얻을Setting the background color on UITableViewHeaderFooterView has been deprecated. Please use contentView.backgroundColor instead.
— 알버트 보리

Xcode6.2 beta5에서도 여전히 동일한 경고가 표시됩니다. UITableViewHeaderFooterView의 생성 방법은 Apple 샘플 코드 인 TVAnimationsGestures와 유사한 xib 로딩을 기반으로합니다. 그러나 Xcode6.2b5를 사용하는 TVAnimationGestures는 경고 메시지를 생성하지 않습니다. Apple 코드에는 '배경'문자열이 전혀 없습니다. 물론 uitableVuewHeaderFooterview.contentView는 TVAnimationsGestures에서 nil입니다. 왜 이런 일이 발생하는지 이해할 수 없습니다.
— kmugitani

7
여전히 경고를받는 사람들을 위해 : UITableViewHeaderFooterView에 IB에 backgroundColor가 설정되어 있지 않은지 확인하십시오.
— Tuslareb

24

iOS 7에서는 contentView.backgroundColor나를 위해 일 tintColor했지만 그렇지 않았습니다.

   headerView.contentView.backgroundColor = [UIColor blackColor];

clearColor나를 위해 작동하지 않았지만 내가 찾은 해결책은 backgroundView속성을 투명한 이미지 로 설정하는 것 입니다. 아마도 누군가에게 도움이 될 것입니다.

UIGraphicsBeginImageContextWithOptions(CGSizeMake(1, 1), NO, 0.0);
UIImage *blank = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

headerView.backgroundView = [[UIImageView alloc] initWithImage:blank];

나는 이것이 @SwiftArchitect의 대답보다 더 나은 접근 방식이라고 생각합니다 (작동했지만). 새로운 UIView를 추가 할 필요가 없다는 사실이 더 좋습니다. 나를 위해 완벽하게 작동했습니다.
— Erick A. Montañez

14

당신의 backgroundColor로 설정해야합니다 contentView당신을 위해 UITableViewHeaderFooterView:

self.contentView.backgroundColor = [UIColor whiteColor];

그러면 작동합니다.


iOS> = 10 전용!. iOS 용 <10 사용 : backgroundView .backgroundColor = UIColor.white
— 피터 Kreinz

12

나를 위해 위에서 언급 한 모든 것을 시도했지만 여전히 "UITableViewHeaderFooterView의 배경색 설정이 더 이상 사용되지 않습니다. 대신 contentView.backgroundColor를 사용하십시오."라는 경고가 표시되었습니다. 그런 다음 이것을 시도했습니다 : xib 파일 내에서 헤더보기의 배경색이 기본값 대신 색상을 지우도록 선택되었습니다. 일단 기본값으로 변경하면 경고가 사라졌습니다. 이것은

이것으로 변경


7

선명한 색상을 위해

self.contentView.backgroundColor = [UIColor clearColor];
self.backgroundView = [UIView new];
self.backgroundView.backgroundColor = [UIColor clearColor];

나에게는 괜찮아 보인다.


1
설정 backgroundView = UIView()후 backgroundColor = .clear유일한 작업 솔루션이었습니다. 감사합니다.
— Vive

7

단색 배경색의 contentView.backgroundColor경우 다음으로 충분해야합니다.

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    if let headerView = view as? UITableViewHeaderFooterView {
        headerView.contentView.backgroundColor = .red // Works!
    }
}

색상을 포함하여 투명도가있는 .clear색상의 경우 더 이상 작동하지 않습니다.

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    if let headerView = view as? UITableViewHeaderFooterView {
        headerView.contentView.backgroundColor = .clear // Does not work 😞
    }
}

전체 투명 섹션 헤더의 경우 backgroundView속성을 빈보기로 설정합니다 .

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    if let headerView = view as? UITableViewHeaderFooterView {
        headerView.backgroundView = UIView() // Works!
    }
}

그러나 가능한 부작용에주의하십시오. 테이블보기가 "그룹화"로 설정되어 있지 않으면 아래로 스크롤 할 때 섹션 머리글이 맨 위에 스냅됩니다. 섹션 헤더가 투명하면 셀 내용이 잘 보이지 않을 수 있습니다.

여기에서 섹션 헤더에는 투명한 배경이 있습니다.

여기에 이미지 설명 입력

이를 방지하려면 섹션 헤더의 배경을 테이블 뷰 또는 뷰 컨트롤러의 배경과 일치하는 단색 (또는 그라데이션)으로 설정하는 것이 좋습니다.

여기에서 섹션 헤더에는 완전히 불투명 한 그라데이션 배경이 있습니다.

여기에 이미지 설명 입력


천재! backgroundView에 대한 빈 UIView를 정의하면 문제가 완전히 해결되었습니다! 감사!
— Luiz Dias


4

에 iOS9 headerView.backgroundView.backgroundColor 나를 위해 일한 :

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    TableViewHeader *headerView = (TableViewHeader *)[super tableView:tableView viewForHeaderInSection:section];
    headerView.backgroundView.backgroundColor = [UIColor redColor];
}

에 iOS8의 내가 사용하던 headerView.contentView.backgroundColor문제없이,하지만 지금은 아이폰 OS 9, 나는 셀의 전체 공간을 채울 배경색을 만든 이상한 문제를 얻고 있었다. 그래서 방금 시도했는데 headerView.backgroundColorOP에서 동일한 오류가 발생했습니다.

UITableViewHeaderFooterView의 배경색 설정은 더 이상 사용되지 않습니다. 대신 contentView.backgroundColor를 사용하세요.

이제 모든 것이 경고없이 잘 작동합니다. headerView.backgroundView.backgroundColor


4

UITableViewHeaderFooterViewwith xibfile 의 사용자 지정 하위 클래스를 만든 경우 setBackgroundColor. 비워 둡니다.

-(void)setBackgroundColor:(UIColor *)backgroundColor {

}

그리고 이것은 당신의 문제를 해결할 것입니다.


이것은 저에게 정답입니다. HeaderFooterView에 배경색을 설정하지 않았지만 콘솔 로그에 경고 메시지가 계속 나타납니다. 너무 짜증나!
— stan liu

4

Storyboard / Nib로 섹션 헤더 셀을 사용자 정의하는 경우 배경색이 기본값 인지 확인하십시오. "테이블 섹션 머리글"보기의 .

그리고 UITableViewHeaderFooterViewnib를 사용하고 하위 클래스 를 만드는 IBOutlet경우 콘텐츠보기에 대한를 만들고 이름을 예를 들어 이름을 지정하는 것입니다. containerView. 이것은 혼동하지 마십시오contentView 컨테이너 뷰의 부모 .

이 설정으로 containerView대신 배경색을 변경합니다 .


1

나는 appearanceWhenContainedIn 체인으로 시도했고 그것은 나를 위해 일했습니다.

[[UIView appearanceWhenContainedIn:[UITableViewHeaderFooterView class], [UITableView class], nil] 
         setBackgroundColor: [UIColor.grayColor]];

1

아마도 backgroundView가 존재하지 않기 때문에

override func draw(_ rect: CGRect){
    // Drawing code
    let view = UIView()
    view.frame = rect
    self.backgroundView = view
    self.backgroundView?.backgroundColor = UIColor.yourColorHere
}

그것은 나를 위해 일합니다.


1

iOS 12, Swift 5. 모양 프록시를 사용하려는 경우 다음 솔루션이 작동합니다.

  1. UITableViewHeaderFooterView를 하위 클래스로 만들고 고유 한 모양 프록시 설정을 노출합니다.
final class MySectionHeaderView: UITableViewHeaderFooterView {
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override init(reuseIdentifier: String?) {
        super.init(reuseIdentifier: reuseIdentifier)
    }

    @objc dynamic var forceBackgroundColor: UIColor? {
        get { return self.contentView.backgroundColor }
        set(color) {
            self.contentView.backgroundColor = color
            // if your color is not opaque, adjust backgroundView as well
            self.backgroundView?.backgroundColor = .clear
        }
    }
}
  1. 원하는 단위로 모양 프록시를 설정합니다.
MySectionHeaderView.appearance().forceBackgroundColor = .red

또는

MySectionHeaderView.appearance(whenContainedInInstancesOf: [MyOtherClass.self]).forceBackgroundColor = .red

1

어려움은 잊어라.

UITableViewHeaderFooterView+BGUpdate.swift아래 코드로 프로젝트에 추가하십시오 .

extension UITableViewHeaderFooterView {

    open override var backgroundColor: UIColor? {
        get {
            return self.backgroundColor
        }
        set {
            let bgView = UIView()
            bgView.backgroundColor = newValue
            backgroundView = bgView
        }
    }
}

사용 은 이전에 예상했던대로 간단합니다.

headerView.backgroundColor = .red

사용 예 :

1) 대리인 tableView:viewForHeaderInSection::

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = tv.dequeueReusableHeaderFooterView(withIdentifier: "MyHeaderView")
    headerView.backgroundColor = .red // <- here
    return headerView
}

또는

2) 사용자 정의 헤더보기 클래스에서 :

class MyHeaderView: UITableViewHeaderFooterView {

    override func awakeFromNib() {
        super.awakeFromNib()
        backgroundColor = .red // <- here
    }
}

좋아 .. 네 방법이 더 낫다. :) 감사합니다
— Eli Burke

1
이 솔루션은 iOS 12에서 재귀 루프를 발생시킵니다.
— Koppacetic

0

명확한 색상으로 BackgroundView를 설정하면 보이는 헤더에 대해 잘 작동합니다. 테이블을 스크롤하여 맨 아래에 머리글을 표시하면이 솔루션이 실패합니다.

PSMy 테이블은 셀이없는 헤더로만 구성됩니다.


0

빠른:

func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView {
    var headerView: TableViewHeader = super.tableView(tableView, viewForHeaderInSection: section) as! TableViewHeader
    headerView.backgroundView.backgroundColor = UIColor.redColor()
}

0

UIView를 만들고 배경색을 설정 한 다음 self.backgroundView로 설정합니다.

- (void)setupBackgroundColor:(UIColor *) color {
    UIView *bgView = [[UIView alloc] initWithFrame:self.bounds];
    bgView.backgroundColor = color;
    self.backgroundView = bgView;
}

0

내 경험을 공유해야한다는 강박감을 느낀다. iOS 10 및 iOS 11에서 잘 작동하는 코드가 있습니다.headerView?.contentView.backgroundColor = .lightGray

그런 다음 갑자기 iOS 9 용 앱을 배포하기로 결정했습니다. 일부 장치가 있기 때문입니다 (iPad mini 일부 이전 세대는 9 이후의 OS로 업데이트되지 않음)-모든 iOS 9, 10 및 11에서 작동하는 유일한 솔루션 다른 모든 헤더 하위보기를 포함하는 헤더의 기본보기를 정의하고 스토리 보드에서 연결하고 backgroundColor 해당 기본보기의를 .

콘센트를 호출하지 않도록 배선 할 때주의해야 할 것입니다. backgroundView일부에는 이미 해당 이름을 가진 속성이 있기 때문입니다.superclass . 나는 나의 것을 불렀다containingView

또한 콘센트 제어를 배선 할 때보기를 클릭하여 배선 Document Outline되지 않았는지 확인하십시오.file owner


0
let bgView = UIView()
bgView.backgroundColor = UIColor.clear
backgroundView = bgView
backgroundColor = UIColor.clear
contentView.backgroundColor = UIColor.clear

질문에 답할 수 있지만 검토를 위해 플래그가 지정되었습니다. 설명이없는 답변은 종종 품질이 낮은 것으로 간주됩니다. 이것이 정답 인 이유에 대한 답변에 몇 가지 설명을 제공하십시오.
— Dan
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.