在我的UITableViewCell
中,我有一個UIButton
和一個已被動態添加到單元格中的標籤。 我也有一個單元格的背景圖像,所以當這個按鈕被點擊時,我想要單元格的背景來替換另一個圖像,或者我希望標籤的文本顏色改變爲其他類似灰色或藍色的東西。如何更改單擊按鈕上的UITableView單元格的背景圖像
這可能嗎?
下面是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;
}
好吧,我明白這一點。但是,我是否需要在這個子類(CustomTableViewCell)中編寫任何代碼? – Ashutosh 2012-04-15 21:26:56
@Ashutosh我編輯了答案,看看如何創建一個自定義單元格。 – 2012-04-15 21:39:40
這看起來像一個很大的努力,因爲一切都已在我的tableview單元格中完成。有沒有一種方法,我可以實現這一點,而不需要子類。 – Ashutosh 2012-04-15 22:12:38