有时候在自定义Cell的时候 会有按钮,而按钮需要交互,有时候是一个按钮,两个按钮,根据实际需求,我这边用自定Cell中 有两个UIButton的控件,获取他们的交互事件。方法很多,我这边使用代理实现
思路:设置UIButton的tag值,这边使用indexPath的section或者indexPath的row来作为UIButton的tag值, 然后在cell中设置代理,在Controller中实现代理就OK。
1.在下面方法中设置UIButton的tag
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *addProjectIdentifier = @"addProjectCell";
[tableView registerClass:[MessageAddProjectsTableViewCell class] forCellReuseIdentifier:addProjectIdentifier];
MessageAddProjectsTableViewCell *addProjectCell = [tableView dequeueReusableCellWithIdentifier:addProjectIdentifier forIndexPath:indexPath];
[addProjectCell loadCellMessageMessageSystemModel:model];
addProjectCell.delegate = self; // 设置代理
addProjectCell.backgroundColor = [UIColor clearColor];
addProjectCell.rejectButton.tag = indexPath.section;
addProjectCell.agreeButton.tag = indexPath.section; // 设置tag值
addProjectCell.selectionStyle = UITableViewCellSelectionStyleNone;
return addProjectCell;
}
2.在cell.h中设置代理
@protocol CellButtonDeleage
/**
* 拒绝添加到项目组
*
* @param button UIBuuton
*/
- (void)rejectAddProjects:(UIButton *)button;
/**
* 同意添加到项目组
*
* @param button UIButton
*/
- (void)agressAddProjects:(UIButton *)button;
@end
@interface MessageAddProjectsTableViewCell : UITableViewCell
@property (assign, nonatomic) id delegate; // 代理
@property (strong, nonatomic) UIButton *rejectButton; // 拒绝按钮
@property (strong, nonatomic) UIButton *agreeButton; // 同意按钮
@end
3.在cell.m中的UIButton交互事件中设置代理传值
/**
* 同意添加到项目组
*
* @param button UIButton
*/
- (void)agreeAction:(UIButton *)button
{
GFBLog(@"同意添加到项目组");
if ([_delegate respondsToSelector:@selector(agressAddProjects:)]) {
button.tag = self.agreeButton.tag;
[_delegate agressAddProjects:button];
}
}
/**
* 拒绝添加到项目组
*
* @param button UIButton
*/
- (void)rejectAction:(UIButton *)button
{
GFBLog(@"拒绝添加到项目组");
if ([_delegate respondsToSelector:@selector(rejectAddProjects:)]) {
button.tag = self.rejectButton.tag;
[_delegate rejectAddProjects:button];
}
}
4.在controller中实现代理方法
#pragma mark - CellButtonDeleage
/**
* 拒绝添加到项目组
*
* @param button UIButton
*/
- (void)rejectAddProjects:(UIButton *)button
{
GFBLog(@"拒绝添加到项目组 delegate");
YJMessageSystemModel *model = [self.messafeSystemArrayModel objectAtIndex:button.tag];
GFBLog(@"消息UUID --- %@", model.uuid);
[self sendRejectOrAgressRequest:model.uuid]; // 网络请求
}
/**
* 同意添加到项目组
*
* @param button UIButton
*/
- (void)agressAddProjects:(UIButton *)button
{
GFBLog(@"同意添加到项目组 delegate");
YJMessageSystemModel *model = [self.messafeSystemArrayModel objectAtIndex:button.tag];
GFBLog(@"消息UUID == %@", model.uuid);
self.agressFlag = YES;
[self sendRejectOrAgressRequest:model.uuid];
}
打印结果
这样就完成了,可以在代理方法中实现UIButton的交互操作,当然也可以才cell的交互事件中实现实现,但是那样耦合性高。我今天刚刚使用这个这个代理来实现,在看博客时候的,看到,就写了下!记录自己的成长过程····如有帮助请笑纳,如有不足,还望提点!谢谢。慢慢会发觉 有思路了 一切就顺了!
今天还遇到一个很愚蠢的事,Cell上的按钮不出来,搞了我一小会,然后看层次结构出来的,我知道被什么遮住,最后是因为拷贝的··多覆盖了一层,由此可见,尽量不要复制代码,有时候好忧伤的!找出来的错误比自己重写一遍还难 谨记…