iPhone + UITableView + разместить изображение для разделителя - PullRequest
2 голосов
/ 09 февраля 2010

У меня в приложении есть UITableView.

Атрибуты: TableStyle = Обычный, SeperatorStyle = одиночный и SeperatorColor = черный

Что я хочу сделать, так это то, что я хочу поместить изображение (маленькую полоску) в качестве разделителя для таблицы.

Пожалуйста, помогите мне.

С уважением, Pratik

Ответы [ 3 ]

23 голосов
/ 28 февраля 2012

Решение, которое сработало для меня.

self.tableView.separatorColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"yourImage"]];
6 голосов
/ 09 февраля 2010

Так, обычно с таблицей iPhone, вы должны просто использовать один из встроенных стилей: http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UITableView_Class/Reference/Reference.html#//apple_ref/occ/instp/UITableView/separatorStyle

Как разработчик iPhone, который шел по этому пути, я предлагаю вам избегать изображений, где это возможно, и использовать API для создания своего приложения.

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

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

Итак, вот реализация функции делегата, которая возвращает ячейку таблицы, используя пользовательский UITableViewCell:

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

  static NSString *CellIdentifier = @"Cell";

  // notice I use a SavedTableCell here instead of a UITavbleViewCell
  SavedTableCell *cell = (SavedTableCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

  if (cell == nil) {
    cell = [[[SavedTableCell alloc] initWithReuseIdentifier:CellIdentifier hasIcon:YES] autorelease];
  }

  // custom function to set the fields in the cell
  [cell setItem:[self.items objectAtIndex:indexPath.row]];  
  return cell;
}

А вот и моя упрощенная реализация SavedTableCell.h:

#import <UIKit/UIKit.h>
#import "Item.h"

@interface SavedTableCell : UITableViewCell {

  // my cell has one label and one image, but yours would have an image placed at the bottom of the cell's frame
  UILabel *primaryLabel;
  UIImageView *icon;
}

// i just made up the class Item... in my code they are actually Waypoints.
- (void) setItem:(Item*)item;


@property(nonatomic,retain) UILabel *primaryLabel;
@property(nonatomic,retain) UIImageView *icon;


@end

А вот упрощенный SavedTableCell.m:

#import "SavedTableCell.h"

@implementation SavedTableCell

@synthesize primaryLabel, icon;


- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier {
  if (self = [super initWithStyle:UITableViewStylePlain reuseIdentifier:reuseIdentifier]) {
    icon = [[UIImageView alloc] initWithFrame:CGRectMake(5,5,40,40)];
    [self.contentView addSubview:icon];
    primaryLabel = [[UILabel alloc]init];
primaryLabel.font = TITLE_FONT;     
    [self.contentView addSubview:primaryLabel]; 
  } 
  return self;
}


- (void) setItem:(Item*)item {
  self.primaryLabel.text = [item name];
  [self.icon setImage:[item imageName]];
}

- (void)layoutSubviews {
  [super layoutSubviews];
  primaryLabel.frame = LABEL_FRAME;
  icon.frame = ICON_FRAME;  
}

- (void)dealloc {
  [icon release];
  [primaryLabel release];
}


@end
0 голосов
/ 18 января 2012

Я хочу просто добавить некоторые мысли к ответу Эндрю Джонсона.

Если вы добавите подпредставление в contentView и используете accesoryView или изображение, тогда оно будет показывать изображение разделителя неправильно. Используйте что-то вроде

UIView *bg = [[UIView alloc] initWithFrame:CGRectMake(5, 5, 40, 40)];
    bg.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.2];
                    //or [UIColor colorWithImagePattern];
                    //or crete UIImageView and assign to backgroundView of the cell
self.backgroundView = bg;
[bg release];
...