Checkbox image toggle in UITableViewCell

前端 未结 6 1438
执念已碎
执念已碎 2020-11-28 02:20

I need some guidance on creating a UITableViewCell that has an image on the left which can be toggled. The image should be tappable and act as a toggle (checkbo

6条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 02:30

    Here's an implementation of the "override touchesBegan:" approach I'm using that is simple and seems to work well.

    Just include this class in your project and create and configure a TouchIconTableViewCell instead of a UITableView cell in your tableView:cellForRowAtIndexPath: method.

    TouchIconTableViewCell.h:

    #import 
    
    @class TouchIconTableViewCell;
    
    @protocol TouchIconTableViewCellDelegate
    
    @required
    - (void)tableViewCellIconTouched:(TouchIconTableViewCell *)cell indexPath:(NSIndexPath *)indexPath;
    
    @end
    
    @interface TouchIconTableViewCell : UITableViewCell {
        id touchIconDelegate;       // note: not retained
        NSIndexPath *touchIconIndexPath;
    }
    
    @property (nonatomic, assign) id touchIconDelegate;
    @property (nonatomic, retain) NSIndexPath *touchIconIndexPath;
    
    @end
    

    TouchIconTableViewCell.m:

    #import "TouchIconTableViewCell.h"
    
    @implementation TouchIconTableViewCell
    
    @synthesize touchIconDelegate;
    @synthesize touchIconIndexPath;
    
    - (void)dealloc {
        [touchIconIndexPath release];
        [super dealloc];
    }
    
    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        CGPoint location = [((UITouch *)[touches anyObject]) locationInView:self];
        if (CGRectContainsPoint(self.imageView.frame, location)) {
            [self.touchIconDelegate tableViewCellIconTouched:self indexPath:self.touchIconIndexPath];
            return;
        }
        [super touchesBegan:touches withEvent:event];
    }
    
    @end
    

    Each time you create or re-use the cell, set the touchIconDelegate and touchIconIndexPath properties. When your icon is touched, the delegate will be invoked. Then you can update the icon or whatever.

提交回复
热议问题