如何在单击按钮时更改UITableView单元格的背景图像

时间:2012-04-15 20:28:35

标签: iphone objective-c uitableview

在我的UITableViewCell我有一个UIButton和一个动态添加到单元格的标签。 我也有一个单元格的背景图像,所以当点击这个按钮时,我想要单元格的背景替换为另一个图像,或者我希望标签的文本颜色更改为灰色或蓝色等其他颜色。

这可能吗?

以下是ny cellForRowAtIndexPath的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        NSArray *subviews = cell.contentView.subviews;
        for (UIView *vw in subviews)
        {
            if ([vw isKindOfClass:[UILabel class]])
            {
                [vw removeFromSuperview];
            }
        }

    NSArray * temp;
    NSData * imageData;
    if (dataToDisplay!=nil) {
        temp = [dataToDisplay objectAtIndex:indexPath.row];
        imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: [temp objectAtIndex:4]]];
    }


    playButtonImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"music_player_play_button.png"]];
    pauseButtonImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"music_player_pause_button.png"]];

   UIButton* preview = [UIButton buttonWithType:UIButtonTypeCustom];
    preview.tag = 100 + indexPath.row;
    [preview addTarget:self
               action:@selector(playPreview:)
     forControlEvents:UIControlEventTouchUpInside];
    preview.backgroundColor = [UIColor clearColor];
    preview.frame = CGRectMake(11,6, 36, 35);
        [preview setBackgroundImage:playButtonImage.image forState:UIControlStateNormal];
    [cell addSubview:preview];

    UILabel * songName = [[UILabel alloc]initWithFrame:CGRectMake(60,15, 150, 15)];
    songName.tag = 100+indexPath.row;
    songName.text = [temp objectAtIndex:5];
    songName.font = [UIFont boldSystemFontOfSize:12];
    songName.backgroundColor = [UIColor clearColor];
    [cell addSubview:songName];

   UIButton * buy = [UIButton buttonWithType:UIButtonTypeCustom];
    [buy addTarget:self
                action:@selector(buySong:)
      forControlEvents:UIControlEventTouchUpInside];
        [buy setImage:[UIImage imageNamed:@"button_buy.png"] forState:UIControlStateNormal];
    buy.tag = 200 + indexPath.row;
    [buy setTitle:@"Buy" forState:UIControlStateNormal];
    buy.titleLabel.font = [UIFont boldSystemFontOfSize:8.0];
    buy.frame = CGRectMake(255,9,41, 30);
    [cell addSubview:buy];
    songsResults.tableHeaderView = headerView;
        UIImage * cellIcon;
    if (indexPath.row==[dataToDisplay count]-1) {
        cellIcon = [UIImage imageNamed:[cellViewImages objectAtIndex:1]];
    }
    else {
        cellIcon = [UIImage imageNamed:[cellViewImages objectAtIndex:0]];
    }
        cell.backgroundView = [[UIImageView alloc]initWithImage:cellIcon];

        cell.clipsToBounds = YES;

    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

2 个答案:

答案 0 :(得分:2)

使用标签作为按下按钮的单元格的标识符。这样您就可以确定需要更改的单元格:

-(void)buySong:(id)sender {
  UIButton *buttonPressed = (UIButton*)sender;
  NSUInteger rowSelected = buttonPressed.tag - 200;
  NSIndexPath *indexPath = [NSIndexPath indexPathForRow:rowSelected inSection:0];
  CustomTableViewCell *cellSelected = (CustomTableViewCell)[self.tableView cellForRowAtIndexPath:indexPath];
  cellSelected.label.textColor = [UIColor redColor];
}

您应该对UITableViewCell进行子类化,以便您可以向其添加新属性并在以后访问它们,就像我对CustomTableViewCell所做的那样。

Here是有关如何创建自定义UITableViewCell的教程。

干杯

答案 1 :(得分:0)

我创建了一个UITableViewCell的子类,它有自己的动作方法来接收按钮点击,并使用一个块来处理该点击,这样你的控制器代码可能如下所示:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SongCell *cell = [tableView dequeueReusableCellWithIdentifier:[SongCell identifier]];
    if (cell == nil) {
        cell = [[SongCell alloc] init];        
    }
    cell.songData = [dataToDisplay objectAtIndex:indexPath.row];
    cell.onPreviewClick =
    ^
    (SongCell *cell)
    {
        cell.isPlaying = YES;
        [self playSongAtIndexPath:indexPath]; // method to start the preview
    };
    return cell
}

为了支持这一点,你的UITableViewCell子类看起来像这样:

// SongCell.h
@interface SongCell : UITableViewCell
@property (nonatomic, strong) NSArray *songData; // NSDictionary would be better
@property (nonatomic, copy) void(^onPreviewClick)(SongCell *cell);
@property (nonatomic, assign) BOOL isPlaying;
+ (NSString *)identifier;
@end

有了这个实现:

// SongCell.m
#import "SongCell.h"
@interface SongData()
@property (nonatomic, strong) NSArray *_songData;
@property (nonatomic, assign) BOOL _isPlaying;
@property (nonatomic, strong) UIButton *playImage;
@property (nonatomic, strong) UIButton *pauseImage;
@property (nonatomic, strong) UIButton *previewButton;
@property (nonatomic, strong) UILabel *songNameLabel;
- (void)previewButtonPressed:(UIButton *)button;
@end

@implementation SongCell
@synthesize onPreviewClick, _songData, _isPlaying, playImage, pauseImage, previewButton, songNameLabel;

- (id)init {
    if ((self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:[SongCell identifier]])) {
        self.selectionStyle = UITableViewCellSelectionStyleNone;

        self.playImage = [UIImage imageNamed:@"music_player_play_button.png"];
        self.pauseImage = [UIImage imageNamed:@"music_player_pause_button.png"];
        self.previewButton = [UIButton buttonWithType:UIButtonTypeCustom];
        previewButton.frame = CGRectMake(11,6, 36, 35);
        [previewButton addTarget:self
                          action:@selector(previewButtonPressed:)
                forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:previewButton];

        self.songNameLabel = [[UILabel alloc]initWithFrame:CGRectMake(60,15, 150, 15)];
        songNameLabel.font = [UIFont boldSystemFontOfSize:12];
        [self addSubview:songNameLabel];
    }
    return self;
}

+ (NSString *)identifier {
    return @"SongCell";
}

- (void)setSongData:(NSArray *)songData
{
    self._songData = songData;
    [self updateSubviews];
}

- (NSArray *)songData {
    return _songData;
}

- (void)setIsPlaying:(BOOL)isPlaying {
    self._isPlaying = isPlaying;
    [self updateSubviews];
}

- (BOOL)isPlaying {
    return _isPlaying;
}

- (void)previewButtonPressed:(UIButton *)button {
    if (onPreviewClick) onPreviewClick(self);
}

- (void)updateSubviews {
    if (_isPlaying) {
        [previewButton setBackgroundImage:pauseImage forState:UIControlStateNormal];
    }
    else {
        [previewButton setBackgroundImage:playImage forState:UIControlStateNormal];
    }
    songNameLabel.text = [_songData objectAtIndex:5];
}

@end
警告:我没有测试过这个。希望它没有太多错误。