UITableViewCell의 배경색을 사용자 정의하는 방법은 무엇입니까?
내 UITableView 내의 모든 UITableViewCells의 배경 (및 테두리도)을 사용자 정의하고 싶습니다. 지금 까지이 물건을 사용자 정의 할 수 없었으므로 기본값 인 흰색 배경 셀이 많이 있습니다.
iPhone SDK로 이것을 수행하는 방법이 있습니까?
셀 contentView의 backgroundColor를 색상으로 설정해야합니다. 액세서리 (공개 화살표 등)를 사용하는 경우 액세서리가 흰색으로 표시되므로 사용자 정의 버전을 롤해야 할 수 있습니다.
다음은이 문제를 해결하기 위해 가장 효율적인 방법입니다. willDisplayCell 대리자 메서드를 사용하십시오 (cell.textLabel.text 및 / 또는 cell.detailTextLabel.text를 사용할 때 텍스트 레이블 배경의 흰색을 처리합니다) ) :
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { ... }
이 대리자 메서드를 호출하면 다음과 같이 셀 색상이 테이블보기가 아닌 셀을 통해 제어됩니다.
- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath { ... }
따라서 셀 대리자 메서드의 본문 내에서 다음 코드를 추가하여 셀의 색상을 바꾸거나 함수 호출을 사용하여 테이블의 모든 셀을 동일한 색상으로 만듭니다.
if (indexPath.row % 2)
{
[cell setBackgroundColor:[UIColor colorWithRed:.8 green:.8 blue:1 alpha:1]];
}
else [cell setBackgroundColor:[UIColor clearColor]];
이 솔루션은 내 환경에서 잘 작동했습니다 ...
OS 3.0은 willDisplayCell 메소드에서 셀의 배경색을 설정하기 때문에 이것은 매우 간단합니다. cellForRowAtIndexPath에서 색상을 설정하지 않아야합니다.
이것은 일반 스타일과 그룹화 스타일 모두에서 작동합니다.
암호:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.backgroundColor = [UIColor redColor];
}
추신 : 여기 willDisplayCell에 대한 문서 추출 :
"테이블보기는 셀을 사용하여 행을 그리기 직전에이 메시지를 대리자에게 전송하므로 대리자가 셀 개체를 표시하기 전에 사용자 지정할 수 있습니다.이 방법을 사용하면 대리자가 이전에 설정 한 상태 기반 속성을 재정의 할 수 있습니다. 선택 및 배경색과 같은 테이블보기. 대리자가 반환 한 후 테이블보기는 알파 및 프레임 속성 만 설정 한 다음 행이 슬라이드 인 또는 슬라이드 아웃 될 때에 만 애니메이션을 적용 할 때만 설정합니다. "
이 게시물 에서이 정보 를 colionel에서 찾았습니다 . 감사합니다!
지금까지 찾은 가장 좋은 방법은 셀의 배경보기를 설정하고 셀 하위보기의 명확한 배경을 설정하는 것입니다. 물론 이것은 액세서리의 유무에 관계없이 색인 스타일 만있는 테이블에서 멋지게 보입니다.
다음은 셀의 배경이 노란색으로 패닝 된 샘플입니다.
UIView* backgroundView = [ [ [ UIView alloc ] initWithFrame:CGRectZero ] autorelease ];
backgroundView.backgroundColor = [ UIColor yellowColor ];
cell.backgroundView = backgroundView;
for ( UIView* view in cell.contentView.subviews )
{
view.backgroundColor = [ UIColor clearColor ];
}
이것을 UITableView 델리게이트 클래스 파일 (.m)에 넣으십시오.
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
UIColor *color = ((indexPath.row % 2) == 0) ? [UIColor colorWithRed:255.0/255 green:255.0/255 blue:145.0/255 alpha:1] : [UIColor clearColor];
cell.backgroundColor = color;
}
Seba와 동의하며 rowForIndexPath 대리자 메소드에서 대체 행 색상을 설정하려고했지만 3.2와 4.2 사이의 결과가 일치하지 않았습니다. 다음은 저에게 효과적이었습니다.
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if ((indexPath.row % 2) == 1) {
cell.backgroundColor = UIColorFromRGB(0xEDEDED);
cell.textLabel.backgroundColor = UIColorFromRGB(0xEDEDED);
cell.selectionStyle = UITableViewCellSelectionStyleGray;
}
else
{
cell.backgroundColor = [UIColor whiteColor];
cell.selectionStyle = UITableViewCellSelectionStyleGray;
}
}
다른 모든 솔루션을 시도한 후 다음 방법이 가장 우아합니다. 다음 델리게이트 방법에서 색상을 변경하십시오.
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if (...){
cell.backgroundColor = [UIColor blueColor];
} else {
cell.backgroundColor = [UIColor whiteColor];
}
}
vlado.grigorov는 좋은 조언을 가지고 있습니다. 가장 좋은 방법은 backgroundView를 만들고 색상을 지정하여 다른 모든 것을 clearColor로 설정하는 것입니다. 또한 그 방법이 색상을 올바르게 지우는 유일한 방법이라고 생각합니다 (샘플을 시도하지만 'yellowColor'대신 'clearColor'를 설정하십시오).
Customizing the background of a table view cell eventually becomes and "all or nothing" approach. It's very difficult to change the color or image used for the background of a content cell in a way that doesn't look strange.
The reason is that the cell actually spans the width of the view. The rounded corners are just part of its drawing style and the content view sits in this area.
If you change the color of the content cell you will end up with white bits visible at the corners. If you change the color of the entire cell, you will have a block of color spanning the width of the view.
You can definitely customize a cell, but it's not quite as easy as you may think at first.
Create a view and set this as background view of the cell
UIView *lab = [[UIView alloc] initWithFrame:cell.frame];
[lab setBackgroundColor:[UIColor grayColor]];
cell.backgroundView = lab;
[lab release];
To extend on N.Berendt's answer - If you want to set cell color based on some state in the actual cell data object, at the time you are configuring the rest of the information for the table cell, which is typically when you are in the cellForRowAtIndexPath method, you can do this by overriding the willDisplayCell method to set the cell background color from the content view background color - this gets around the issue of the disclosure button backgrounds etc. not being right but still lets you control color in the cellForRowAtIndexPath method where you are doing all of your other cell customisation.
So: If you add this method to your table view delegate:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.backgroundColor = cell.contentView.backgroundColor;
}
Then in your cellForRowAtIndexPath method you can do:
if (myCellDataObject.hasSomeStateThatMeansItShouldShowAsBlue) {
cell.contentView.backgroundColor = [UIColor blueColor];
}
This saves having to retrieve your data objects again in the willDisplayCell method and also saves having two places where you do tailoring/customisation of your table cell - all customisation can go in the cellForRowAtIndexPath method.
Create an image to use as background with Photoshop or gimp and name it myimage. Then, add this method to your tableViewController class:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
UIImage *cellImage = [UIImage imageNamed:@"myimage.png"];//myimage is a 20x50 px with gradient color created with gimp
UIImageView *cellView = [[UIImageView alloc] initWithImage:cellImage];
cellView.contentMode = UIContentViewModeScaleToFill;
cell.backgroundView = cellView;
//set the background label to clear
cell.titleLabel.backgroundColor= [UIColor clearColor];
}
This will work also if you have set the UITableView to custom in attribute inspector.
My solution is to add the following code to the cellForRowAtIndexPath event:
UIView *solidColor = [cell viewWithTag:100];
if (!solidColor) {
solidColor = [[UIView alloc] initWithFrame:cell.bounds];
solidColor.tag = 100; //Big tag to access the view afterwards
[cell addSubview:solidColor];
[cell sendSubviewToBack:solidColor];
[solidColor release];
}
solidColor.backgroundColor = [UIColor colorWithRed:254.0/255.0
green:233.0/255.0
blue:233.0/255.0
alpha:1.0];
Works under any circumstances, even with disclosure buttons, and is better for your logic to act on cells color state in cellForRowAtIndexPath than in cellWillShow event I think.
Subclass UITableViewCell and add this in the implementation:
-(void)layoutSubviews
{
[super layoutSubviews];
self.backgroundColor = [UIColor blueColor];
}
UIView *bg = [[UIView alloc] initWithFrame:cell.frame];
bg.backgroundColor = [UIColor colorWithRed:175.0/255.0 green:220.0/255.0 blue:186.0/255.0 alpha:1];
cell.backgroundView = bg;
[bg release];
This will work in the latest Xcode.
-(UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath {
cell.backgroundColor = [UIColor grayColor];
}
Try this:
- (void)tableView:(UITableView *)tableView1 willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
[cell setBackgroundColor:[UIColor clearColor]];
tableView1.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed: @"Cream.jpg"]];
}