uibutton响应传参数
来源:互联网 发布:mac山狮系统 编辑:程序博客网 时间:2024/05/20 04:15
转载自:http://innovatence.com/?p=196
开发过程中,有些初学者经常会问,如何调用UIButton的响应时传入一个参数,但是,
- (void)addTarget:(id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
方法是无法传参数的,能得到的只是响应的UIButton。下面我们来学习一下如何通过UIButton来“传参数”。 我们以UITableView 为例,在UITableViewCell中定义一个cell,我们称之为CustomCell,cell上加有一个UIButton的控件。我们要做的是如何在点击UIButton时获得cell。可以通过以下两种方法实现。
1. 使用delegate 首先,在CustomCell类文件中定义protocol,有如下定义
@protocol CustomCellProtocol - (void)customCell:(CustomCell *)cell didTapButton:(UIButton *)button;@end
将UIButton的响应加在CustomCell文件中,比如这个响应叫做
- (IBAction)buttonTarget:(id)sender;
那么在点击button时,就会调用这个方法。这个方法可以实现如下,
- (IBAction)buttonTarget:(id)sender{ if ([self.delegate respondsToSelector:@selector(customCell:didTapButton:)]) { [self.delegate performSelector:@selector(customCell:didTapButton:) withObject:self withObject:self.button]; }}
然后在UIViewController里实现代理方法,这样,就能获得这个UIButton所在的UITableViewCell。
2. 在ViewController中添加响应 第二种方法时在
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
方法中直接给UIButton添加响应。实现如下,
-(UITableViewCell *)tableView:(UITableView *)atableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ CustomCell *cell = [atableView dequeueReusableCellWithIdentifier:@"CustomCell"]; [cell.button addTarget:self action:@selector(didTapButton:) forControlEvents:UIControlEventTouchUpInside];return cell;}
那么点击button时就会调用
- (void)didTapButton:(UIButton *)sender
剩下的就是如何通过这个sender获得它所在的cell。我们这么实现这个方法,
- (void)didTapButton:(UIButton *)sender{ CGRect buttonRect = sender.frame; for (CustomCell *cell in [tableView visibleCells]) { if (CGRectIntersectsRect(buttonRect, cell.frame)) { //cell就是所要获得的 } }}
- uibutton响应传参数
- uibutton响应传参数
- iOS菜鸟学习——UIButton响应传参数
- UIButton 双击事件响应
- UIButton增大响应区域
- UIButton增加响应区域
- UIButton多参数传值实现
- iOS UIButton长按响应
- UIButton不响应原因总结
- UIButton点击无法响应事件
- UIButton的响应点击事件
- UIButton无法响应点击事件
- 修改UIButton响应热区
- UIButton 扩大点击响应区域
- UIButton 不响应或延迟响应 UIControlEventTouchDown
- UIButton 不响应或延迟响应 UIControlEventTouchDown
- UIButton sender参数
- UIButton 传递参数
- Linux top命令手册
- poj 3041 网络流做法 sap+gap
- Java高新技术之反射
- Windows CE设备:矩阵键盘开发
- 渊子赛马 tzc
- uibutton响应传参数
- MATLAB中mexFunction函数的接口规范
- Java高新技术之内省与JavaBean
- 2003 cant connect to MySQL server on 'localhost'(10061)
- 各大面试题
- 旧工程适配iOS6和iPhone5的一些故事
- CheckBoxList 两列并排 编译为表格显示
- Difference between CPPFLAGS and CXXFLAGS in GNU Make
- matlab与VS2010混合编程时,char16_t redefinition错误