我有一個UITableViewCell的子類,我遇到了滾動問題。所有的子視圖都被添加到故事板中的單元格中,除了一個UIView。我想根據條件添加這個UIView作爲單元格的子視圖。問題是,當單元格滾動到屏幕上時,UIView會再次添加到單元格中,或添加到錯誤的單元格中。這是我的代碼,你能告訴我我做錯了什麼嗎?UITableViewCell子視圖滾動時添加到錯誤的單元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
WavesFeedCell *cell = (WavesFeedCell *)[tableView dequeueReusableCellWithIdentifier:WavesFeedCellIdentifier forIndexPath:indexPath];
cell.cellWaveObject = [self.wavesArray objectAtIndex:indexPath.row];
//set the frames and text for the labels
cell.timeStampLabel.text = @"14m";
cell.waveTextLabel.text = cell.cellWaveObject.waveString;
cell.wavedByLabel.text = [NSString stringWithFormat:@"Waved by %@", cell.cellWaveObject.wavedByString];
//round the corners of the image view
[self setCornerRadiusForImageView:cell.profilePictureImageView];
//does the wave object have any agrees?
if (cell.cellWaveObject.numberOfAgrees > 0)
{
UIView *agreedView = [[UIView alloc] init];
UILabel *numberOfAgreesLabel = [[UILabel alloc] init];
numberOfAgreesLabel.font = [UIFont boldSystemFontOfSize:13.0f];
numberOfAgreesLabel.textColor = [UIColor whiteColor];
if (cell.cellWaveObject.numberOfAgrees > 1)
{
numberOfAgreesLabel.text = [NSString stringWithFormat:@"+%i Agree", cell.cellWaveObject.numberOfAgrees];
}
else
{
numberOfAgreesLabel.text = [NSString stringWithFormat:@"+%i Agrees", cell.cellWaveObject.numberOfAgrees];
}
UIImageView *backgroundImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:AgreedViewImage]];
//get the width of the string
CGSize constraintSize = CGSizeMake(242.0f, 16.0f);
CGSize stringSize = [numberOfAgreesLabel.text sizeWithFont:numberOfAgreesLabel.font constrainedToSize:constraintSize];
CGFloat agreedViewWidth = stringSize.width + 10.0f;
//adjust the frame and add it to the cell
agreedView.frame = CGRectMake(310.0f - agreedViewWidth, cell.wavedByLabel.frame.origin.y, agreedViewWidth, 14.0f);
backgroundImageView.frame = CGRectMake(5.0f, 0.0f, agreedView.frame.size.width, agreedView.frame.size.height);
numberOfAgreesLabel.frame = CGRectMake(5.0f, 0.0f, agreedView.frame.size.width, agreedView.frame.size.height);
[agreedView addSubview:backgroundImageView];
[agreedView addSubview:numberOfAgreesLabel];
[cell.contentView addSubview:agreedView];
return cell;
}
else
{
return cell;
}
}
更好地設置在子類的UITableView細胞的類 –