Размер фона UITableViewCell - PullRequest
       24

Размер фона UITableViewCell

3 голосов
/ 23 февраля 2010

Я пытаюсь установить размер моего фона немного короче, чем по умолчанию, создавая некоторое пространство между ячейками. Это оказалось трудным. Установка рамки фонового представления, похоже, ничего не делает:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{ 
    NSString *reuseIdentifier = @"cell";
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:reuseIdentifier];

    if (!cell)
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];

    // Set up the cell...

    cell.contentView.backgroundColor = [UIColor clearColor];

    cell.backgroundView = [[[UIView alloc] initWithFrame:CGRectMake(0, 4, 320, 42)] autorelease];
    cell.backgroundView.backgroundColor = [UIColor blackColor];
    cell.backgroundView.alpha = .2;

    cell.selectedBackgroundView = [[[UIView alloc] initWithFrame:CGRectMake(0, 4, 320, 42)] autorelease];
    cell.selectedBackgroundView.backgroundColor = [UIColor whiteColor];
    cell.selectedBackgroundView.alpha = .2;

    cell.font = [UIFont fontWithName:@"MarkerFelt-Thin" size:22.0f];
    cell.selectedTextColor = [UIColor blackColor];
    cell.textColor = [UIColor whiteColor];

    NSDictionary *dict = [files objectAtIndex:indexPath.row];

    cell.text = [dict objectForKey:@"name"];

    return cell;
}

Любая помощь?

Кроме того, установка выбранного фонового представления ничего не делает. Когда ячейка выбрана, фон будет полностью пустым. Почему это?

Я использую iPhone OS 2.2.1.

Я тоже так делаю:

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.rowHeight = 50.0f;
}

Вы можете скачать код здесь (сделал небольшой проект только для этой проблемы):

http://dl.dropbox.com/u/608462/tabletest2.zip

Ответы [ 11 ]

3 голосов
/ 14 октября 2011

backgroundView - это не обычный вид, что-то происходит за кулисами. Проверьте эту ссылку:

Разница между фоновым представлением и представлением содержимого в uitableviewcell

Конкретно из документации:

backgroundView: По умолчанию это nil для ячеек в таблицах простого стиля (UITableViewStylePlain) и не nil для таблиц сгруппированных стилей UITableViewStyleGrouped) UITableViewCell добавляет фоновое представление как подпредставление позади всех других представлений и использует его текущее местоположение кадра.

Следовательно: на самом деле он не имеет местоположения кадра, он использует местоположение ячейки.

Этот код работал:

UIImageView *bgView = [[UIImageView alloc] init]; // Creating a view for the background...this seems to be required.
bgView.backgroundColor = [UIColor redColor];
cell.backgroundView = bgView;

UIImageView *bgImageView = [[UIImageView alloc] init]; // Creating a subview for the background...
bgImageView.backgroundColor = [UIColor colorWithWhite:1 alpha:1];
[bgImageView setFrame:CGRectInset(cell.bounds, 1, 1)];

[cell.backgroundView addSubview:bgImageView]; // Assigning the subview, and cleanup.
[bgImageView release];
[bgView release];

Потратил около часа, пытаясь выяснить это ... но это работает. Это код в методе делегата cellForRowAtIndexPath - здесь я, очевидно, не буду описывать все это.

3 голосов
/ 05 октября 2012
Решение

Морганкодов привело меня в правильном направлении.

Я добавил подслой к фоновому виду и стилизовал его. При установке цвета фона для представления фона в clearColor, подслой является единственным показанным.

UIView *backgroundView = [[UIView alloc] init];
backgroundView.backgroundColor = [UIColor clearColor];

CALayer *sublayer = [CALayer layer];
sublayer.backgroundColor = [UIColor colorWithWhite:1 alpha:0.8].CGColor;
sublayer.frame = CGRectMake(15, 3, tableView.frame.size.width - 45, 38);
sublayer.cornerRadius = 5;
[backgroundView.layer addSublayer:sublayer];

cell.selectedBackgroundView = backgroundView;
2 голосов
/ 21 августа 2012

Еще один подход: добавьте подслой к своему фону. Я добавил следующее к инициализации подкласса UITableViewCell, и это, кажется, прекрасно работает.

  UIView* backgroundView = [[UIView alloc] initWithFrame: self.contentView.frame ];

  backgroundView.layer.frame = CGRectInset(backgroundView.layer.frame, 20, 20);

  CALayer *sublayer = [CALayer layer];
  sublayer.backgroundColor = [UIColor colorWithWhite:0.69 alpha:1].CGColor;
  sublayer.frame = CGRectMake(INDENT, 0, width - (INDENT * 2), [ChuckWagonTableViewCellCell cellHeight]) ;
  [backgroundView.layer addSublayer:sublayer];

  self.selectedBackgroundView = backgroundView;
2 голосов
/ 23 февраля 2010

Этот метод совершенно отличается от того, что вы пытаетесь сделать.

Одна вещь, которую мне нравится делать, - это использовать собственное изображение для backgroundView и selectedBackgroundView, а не позволять iPhone обрабатывать задачи раскраски.Это дает мне гораздо больше гибкости при отображении ячейки.Все, что нужно, это добавить что-то вроде этого:

  cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"normal.png"]];
  cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"selected.png"]];

To:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
1 голос
/ 14 июня 2011

Когда возиться с фоновым видом, я делал бы это: - (void) tableView: (UITableView *) tableView willDisplayCell: (UITableViewCell *) ячейка дляRowAtIndexPath: (NSIndexPath *) indexPath {

а не в: - (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath {

1 голос
/ 23 февраля 2010

Попробуйте это:

UIView *bg = [[UIView alloc] initWithFrame: CGRectInset(cell.frame, 0.0, 2.0)];
bg.backgroundColor = [UIColor whiteColor];
cell.backgroundView = bg;

Также не забудьте установить цвет фона и цвет разделителя для очистки в viewDidLoad ():

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.backgroundColor = [UIColor clearColor];
}
0 голосов
/ 08 февраля 2016

Попробуйте добавить подпредставление в свои backgroundViews, а не изменять их напрямую:

UIView *selectedView = [[UIView alloc] initWithFrame:UIEdgeInsetsInsetRect(cell.frame, UIEdgeInsetsMake(8, 8, 8, 8))];
selectedView.backgroundColor = [UIColor redColor];
cell.selectedBackgroundView = [UIView new];
cell.selectedBackgroundView.backgroundColor = [UIColor clearColor];
[cell.selectedBackgroundView addSubview:selectedView];

У меня была такая же проблема, как у вас с selectedBackgroundView, и это сработало для меня;)

0 голосов
/ 10 апреля 2014

Возможным решением может быть создание подкласса UIView и добавление аргументов цвета и высоты (если вы хотите изменить только высоту, иначе вы можете передать размер / прямоугольник). Обратите внимание, что необходимо установить цвет фона, иначе вы увидите пустую область.

- (id)initWithColor:(UIColor *)color height:(CGFloat)height backgroundColor:(UIColor *)backgroundColor;
{
    self = [super init];

    if (self != nil)
    {
        _color = color;
        _height = height;
        _backgroundColor = backgroundColor;
    }

    return self;
}

Добавьте соответствующие свойства:

@interface CellSelectedBackgroundView ()
@property (strong, nonatomic) UIColor *color;
@property (strong, nonatomic) UIColor *backgroundColor;
@property (assign, nonatomic) CGFloat height;
@end

А в drawRect: вы можете заполнить область:

- (void)drawRect:(CGRect)rect
{
    [self.backgroundColor setFill];
    UIRectFill(rect);

    [self.color setFill];
    CGRect frame = CGRectMake(0, 0, self.bounds.size.width, self.height);

    UIRectFill(frame);
}

Просто инициализируйте пользовательский подкласс UIView и установите его в качестве свойства selectedBackgroundView вашего UITableViewCell.

0 голосов
/ 31 мая 2011

У меня была похожая проблема, и ни один из ответов, казалось, не подходил для моего случая. В этом случае все мои ряды имеют одинаковую высоту, но с некоторой математикой это можно адаптировать для размещения рядов с разной высотой.

Я установил высоту в моем контроллере, используя метод UITableViewDelegate. У меня на контроллере есть переменная экземпляра cellBackgroundImage, которая является UIImage, которая будет использоваться для фона UITableViewCell. Фон UITableView установлен на [UIColor clearColor].

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return cellBackgroundImage.size.height + SPACING_HEIGHT;
}

Где SPACING_HEIGHT - постоянная #define для высоты зазора.

Тогда уловка заключалась в том, чтобы использовать UIView, который обернул бы UIImageView, который будет фоном ячейки. Я сделал это, выполнив:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ContentCell"];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"ContentCell"] autorelease];
        CGFloat height = [self tableView:tableView heightForRowAtIndexPath:indexPath];
        cell.frame = CGRectMake(0, 0, [UIScreen mainScreen].applicationFrame.size.width, height);
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        UIView *backView = [[UIView alloc] initWithFrame:CGRectInset(cell.frame, 0, 0)];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:cellBackgroundImage];
        [backView insertSubview:imageView atIndex:0];
        cell.backgroundView = backView;
        [backView release];
        [imageView release];
    }

    return cell;
}

Затем, установив cell.backgroundView = backView на UIView с UIImageView, который содержит мой фон, мне удалось добиться эффекта разрыва между строками. Надеюсь, это поможет.

0 голосов
/ 26 марта 2010

То, что я думаю, происходит: когда вы выбираете строку, внутреннее значение альфа выбранного фонового обзора равно se 1, что делает его полностью белым.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...