开发者

Cant display button on specific rows of UITableView properly for iPhone

开发者 https://www.devze.com 2022-12-28 18:33 出处:网络
I am trying to have a button for selected rows of my table. Here is the example code I am using: - (UITableViewCell *)tableView:(UITableView *)tableView

I am trying to have a button for selected rows of my table.

Here is the example code I am using:

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

    static NSString *ControlRowIdentifier = @"ControlRowIdentifier";

    UITableViewCell *cell = [tableView 
                             dequeueReusableCellWithIdentifier:ControlRowIdentifier];

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                       reuseIdentifier:ControlRowIdentifier] autorelease];
    }

    if ([indexPath row] > 5) {

        UIImage *buttonUpImage = [UIImage imageNamed:@"button_up.png"];
        UIImage *buttonDownImage = [UIImage imageNamed:@"button_down.png"];
        UIButton *but开发者_StackOverflow中文版ton = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(0.0, 0.0, buttonUpImage.size.width, buttonUpImage.size.height);
        [button setBackgroundImage:buttonUpImage forState:UIControlStateNormal];
        [button setBackgroundImage:buttonDownImage forState:UIControlStateHighlighted];
        [button setTitle:@"Tap" forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
        cell.accessoryView = button;

    }

    NSUInteger row = [indexPath row];
    NSString *rowTitle = [list objectAtIndex:row];
    cell.textLabel.text = rowTitle;

    return cell;
} 

This code works absolutely fine when loaded for 1st time. So, as per the logic it shows 'Tap' button for all rows greater than 5.

Problem occurs when I scroll up and down. Once I do that it just starts putting that button at any random row. I dont understand why it does that and it'll be really helpful if someone can give some tips on this.

Thanks.


The problem is reusing cell's identifier. In your case, the cell with an index of less than 6 must be with one identifier, and the rest from other.


Table view cells is reusable objects and you must do some clean work with it. Try use next:

if ([indexPath row] > 5) {

    ...


} else {
    cell.accessoryView = nil;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号