对 UITableView 中的按钮执行操作
我在 UITableViewCell 中有一个 UIButton... 我想在 UIButton 上执行操作。
我需要将数据发送到为此按钮注册的 @selector 方法,以便我可以在用户按下此按钮时执行操作。
如何实现这一点,尽管我发现选择器函数内的 (id) sender
参数并不总是在 cellForRowAtIndexPath
函数中创建的原始按钮。
在 cellForRowAtIndexPath
函数内部:
UIImage* pdfImage = [UIImage imageNamed:@"icon_pdf.png"];
UIButton* pdfButton = [UIButton buttonWithType:UIButtonTypeCustom];
[pdfButton setImage:pdfImage forState:UIControlStateNormal];
pdfButton.accessibilityHint = @"path/to/pdf/file";
pdfButton.frame = CGRectMake(0, 0, 40, 40);
[pdfButton addTarget:self action:@selector(openUrlInBrowser:) forControlEvents:UIControlEventTouchUpInside];
cell.accessoryView = pdfButton;
这是发送者函数:
-(void) openUrlInBrowser:(id)sender
{
NSLog(@"%@", [sender class]);
NSString * url=[sender accessibilityHint];
NSLog(@"%@",url);
NSLog(@"%@",sender);
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]];
}
I've a UIButton in UITableViewCell...
I want to perform an action on the UIButton..
I need to send data to the @selector method that is registered for this button so that I can perform actions on when the user press this button.
How to accomplish that, though I found that the (id) sender
parameter inside the selector function is not always the original button created in cellForRowAtIndexPath
function.
Inside the cellForRowAtIndexPath
function:
UIImage* pdfImage = [UIImage imageNamed:@"icon_pdf.png"];
UIButton* pdfButton = [UIButton buttonWithType:UIButtonTypeCustom];
[pdfButton setImage:pdfImage forState:UIControlStateNormal];
pdfButton.accessibilityHint = @"path/to/pdf/file";
pdfButton.frame = CGRectMake(0, 0, 40, 40);
[pdfButton addTarget:self action:@selector(openUrlInBrowser:) forControlEvents:UIControlEventTouchUpInside];
cell.accessoryView = pdfButton;
Here's the sender function:
-(void) openUrlInBrowser:(id)sender
{
NSLog(@"%@", [sender class]);
NSString * url=[sender accessibilityHint];
NSLog(@"%@",url);
NSLog(@"%@",sender);
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
希望我正确理解这个问题 - 我通常在 uitableview 中添加的按钮上定义一个标签,它是行的索引。在 cellForRowAtIndexPath 中:
然后您可以将其返回到目标方法中:
并使用以下方式查询单元格中的值进行处理:
或者,您可以通过访问发送者的超级视图来获得相同的结果,但我发现这更难以调试。
Hoping I understand correctly the question - I ususally define a tag on the button added in the uitableview which is the index of the row. In cellForRowAtIndexPath :
You can then get it back in the target method :
And query the values in the cell for your processing using :
Alternatively you could get the same result by accessing the superviews of the sender but I find this more difficult to debug.
我更喜欢使用:
它不依赖于表格中的单元格位置
I prefer to use:
it not depend on cell position in the table