您的位置:首页 > 其它

自定义Cell上的按钮--delegate协议的实现

2013-12-06 16:25 239 查看
前两天看了一些关于delegate的东西

在以前的时候,老师上课也讲过,但是我们自己从来没用过,应该是没有想到过用它

就算老师讲的demo里面涉及的有,我就直接抄过来,也懒得考虑为什么要用它?怎么用才合适

cell.h

#import <UIKit/UIKit.h>

@protocol MyCellDelegate;

@interface ZMCell :UITableViewCell

@property(weak,nonatomic)id <MyCellDelegate>delegate;

-(void)customlizedWithData:(id)data findAllname:(NSArray *)array;

@end
@protocol MyCellDelegate <NSObject>
-(void)TapSomeButtons:(UIButton *)sender;

@end
cell.m

-(void)TapRowBtn:(id)sender
{
UIButton *btn = (UIButton *)sender;
if ([self.delegaterespondsToSelector:@selector(TapSomeButtons:)])
{
[self.delegateTapSomeButtons:btn];
}
}
设置一个delegate,让Controller去做Cell上按钮的事情
当delegate响应你在协议里面定义的方法的时候,就把按钮传过去(传到ViewController里面)
在这里面

-(ZMCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath
staticNSString *CellIdentifier =@"cellID";
ZMCell * cell = [tableViewdequeueReusableCellWithIdentifier:CellIdentifier];
if (cell ==nil)
{

cell = [[ZMCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:CellIdentifier];
}
cell.delegate = self;
NSNumber * number = [[NSNumberalloc]init];
number = [NSNumbernumberWithInt:indexPath.row ];

[cell customlizedWithData:numberfindAllname:tableArr];
NSLog(@"%@",number);

return cell;
记住了,血的教训
我把cell.delegate = self;写在了 if (cell
== nil)之前
delegate是空的,我找了两个多小时,确定自己的delegate没有写错,也没有出现任何问题
高手过来一看,就说你得delagate放在 if (cell
== nil)之前,它可能是空的,所以delegate也可能是空的
把它换个位置就不会出现这样的问题了
响应delegate方法

-(void)TapSomeButtons:(UIButton *)sender
{
UIButton *btn = (UIButton *)sender;

//
根据tag获取整条信息
ZMTable *table = [tableArrobjectAtIndex:btn.tag];

btn.selected = !btn.selected;

selectRoomAndTabelTag = [NSStringstringWithFormat:@"%d%d",table.roomid,btn.tag];

JDGSQLiteUtil *sqlite = [JDGSQLiteUtilsharedInstance];
[sqliteopenDatabase:@"A.DB"];

//
更新数据

int i= [selectRoomAndTabelTagintValue];

//点击选中按钮的时候
if (btn.selected)
{

[sqlite exec:[NSStringstringWithFormat:@"UPDate
Table1 set isBusy = '1' WHERE Tableid = '%d'",i]];
}

//
再一次点击没有选中时
if (!btn.selected)
{

[sqlite exec:[NSStringstringWithFormat:@"UPDate
Table1 set isBusy = '0' WHERE Tableid = '%d'",i]]; }

//查找当isBusy是1的时候

NSArray *selecttableID = [sqlitequery:@"SELECT Tableid FROM Table1 where isBusy
= '1' "decode:bDecode];
NSLog(@"已选中的桌子%@",selecttableID);

//默认存在数据库A.DB
BOOL isExisted = [sqlite
existDB:@"A.DB"];

//
如果不存在
if (!isExisted )
{
UIAlertView * alert = [[UIAlertViewalloc]initWithTitle:@"提示"message:@"数据库操作失败"
delegate:selfcancelButtonTitle:@"确定" otherButtonTitles:@"取消",nil];
[alertshow];

[btn setBackgroundImage:[UIImageimageNamed:@"free"]forState:UIControlStateNormal];
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: