dengApro
dengApro

Reputation: 4038

How to achieve the effect of UITableViewCell selection by clicking a button in UITableViewCell?

I have a menuView in a list view controller. The menuView added on the UITableViewCell when a more button in the cell being taped.

imageHere

It is easy to achieve with singleton. Here is code:

@implementation ProductsOperationMenu
static ProductsOperationMenu *_instance;
+ (instancetype)sharedInstance{

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] initWithFrame:CGRectZero];
    });
    return _instance;
}


- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self setup];
    }
    return self;
}

ZBMyProductsCell.m

@implementation ZBMyProductsCell

- (void)awakeFromNib
{
    [super awakeFromNib];
    _operationMenu = [[ProductsOperationMenu alloc] initWithFrame: CGRectZero];
}

- (IBAction)operationButtonClick:(UIButton *)sender {
    if ([self.contentView.subviews containsObject:_operationMenu]) {
        _operationMenu.hidden = ![_operationMenu isHidden];
    } else{
        [self.contentView addSubview:_operationMenu];
        _operationMenu.hidden = NO;
    }

    [_operationMenu mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(205);
        make.height.mas_equalTo(60);
        make.bottom.mas_equalTo(self.operationButton).offset(0);
        make.right.mas_equalTo(self.operationButton.mas_left).offset(-10);
    }];
}

I think it is singleton abuse. I want to improve the code.

Without singleton, the code and effect:

@implementation ProductsOperationMenu
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self setup];
    }
    return self;
}

imageTwo

I think I have to handle the message sending between cells. When one cell's button being clicked, the menu view of others must hide.

I think it is quite similar to cell's selection. When one cell is being selected , the previous selected one's effect dismissed.

None or one

So how to achieve the effect of UITableViewCell selection by clicking a button in UITableViewCell?

Upvotes: 1

Views: 53

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100549

Make a global integer that contains the currently index of cell being clicked and when any button in cell is being clicked change the index and reload the tableView -- in cellForRow

 if(indexpath.row == index)
 {

    cell.menuView.isHidden = false
 }
 else
 {

    cell.menuView.isHidden = true
 }

Edit :

If you want to animate hide of menuView when another is selected then you must make the tableview global and access his visible cells and animate alpha of menuView with duration

Upvotes: 1

Related Questions