starwar2012 2013-03-06 02:05 采纳率: 0%
浏览 3194
已采纳

点击按钮时实现调用方法

有一个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中类中。

  • 写回答

2条回答

  • ReyZhang 移动开发领域新星创作者 2013-03-07 13:01
    关注

    这里就需要用到“代理协议”的方法来解决这个问题
    首先在你的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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog