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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘