自定義Cell上的按鈕--delegate協議的實現

前兩天看了一些關於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]];    }

    //查找當isBusy1的時候

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

    }


}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章