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 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛