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

心已入冬 提交于 2019-12-13 04:35:25

问题


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

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;
}

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?


回答1:


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



来源:https://stackoverflow.com/questions/48341041/how-to-achieve-the-effect-of-uitableviewcell-selection-by-clicking-a-button-in-u

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!