点击按钮时实现调用方法
问题描述:
有一个CustomCell,想实现在点击它所在按钮时会发出警报。不知道怎么访问这个方法?
@interface CustomCell : UITableViewCell {
IBOutlet UIImageView *imageViewCell;
IBOutlet UILabel *theTitle;
IBOutlet UIButton*imageButton;
}
@property(nonatomic,retain) IBOutlet UIButton*imageButton;
@property(nonatomic,retain) UIImageView *imageViewCell;
@property(nonatomic,retain) UILabel *theTitle;
-(IBAction)imageButtonAction;
@end
@implementation CustomCell
@synthesize imageViewCell;
@synthesize theTitle;
-(IBAction)imageButtonAction{
}
不是要在这里调用方法,我希望的是方法在使用CustomCell中类中。
答
这里就需要用到“代理协议”的方法来解决这个问题
首先在你的CustomCell的.h头文件中定义一个“协议”protocol ,并在CustomCell中添加一个delegate的属性
@protocol CustomCellDelegate <NSObject>
//创建一个当点击imagebutton时显示title的信息
-(void)showTitle:(NSString *)title;
@end
@protocol CustomCellDelegate;
@inertface CustomCell: UITableViewCell
//多添加一个属性
@property (nonatomic,assign) id <CustomCellDelegate> delegate;
@end
在.m实现文件的imagebutton click事件中
@implementation CustomCell
@synthesize delegate;
//imagebutton的点击事件
-(IBAction)imageButtonAction {
if ([delegate isRespondToSelector:@selector(showTitle:)]) {
[delegate showTitle:theTitle.text]; //将UILabel的内容传递到消息接收者
}
}
@end
在带有CustomCell的UITableView 所在的viewController 的.h头文件中添加CustomCellDelegate 的协议
@interface myViewController:UIViewController <CustomCellDelegate>
@end
在viewController 的.m实现文件中,UITableView 的datasource 协议方法中:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*) indexPath {
CustomCell *cell=[[[CustomCell alloc] init] autorelease];
cell.delegate=self; //指明CustomCell的代理为当前的viewController
............ //todo
return cell;
}
//实现CustomCellDelegate的协议方法
-(void)showTitle:(NSString *)title {
NSLog("the cell title is :%@",title);
}
答
你自己定义一个listener不就OK么?