Use IBAction from UIButton inside custom cell in main view controller(在主视图控制器的自定义单元格中使用来自 UIButton 的 IBAction)
问题描述
我创建了一个带有自己的 .m、.h 和 .xib 文件的自定义单元格.在单元格中,我有一个 UIButton,已添加到 IB 中的 xib.
I have created a custom cell with its own .m, .h and .xib file. In the cell, I have a UIButton that I added to the xib in IB.
我可以在此自定义单元格的 .m 中从 UIButton 接收 IBAction,但实际上,我想将该按钮按下转发到托管表格(以及自定义单元格)的主视图 .m 并使用那里有一个动作.
I can receive the IBAction from the UIButton in this custom cell's .m, but really, I'd like to be forwarding that button press to the main view .m that is hosting the table (and so custom cell) and use an action there.
在过去的 4 个小时里,我一直在尝试各种方法 - 我应该使用 NSNotificationCenter 吗?(我已经尝试了很多通知,但无法让它工作,并且不确定我是否应该坚持下去)
I've spent the last 4 hours attempting various ways of doing this - should I be using NSNotificationCenter? (I've tried Notifications lots but can't get it to work and not sure if i should be persevering)
推荐答案
需要在cell的.h文件中使用delegate.像这样声明委托
You need to use delegate in .h file of cell. Declare the delegate like this
@class MyCustomCell;
@protocol MyCustomCellDelegate
- (void) customCell:(MyCustomCell *)cell button1Pressed:(UIButton *)btn;
@end
然后声明字段和属性
@interface MyCustomCell:UItableViewCell {
id<MyCustomCellDelegate> delegate;
}
@property (nonatomic, assign) id<MyCustomCellDelegate> delegate;
@end
在 .m 文件中
@synthesize delegate;
按钮方法
- (void) buttonPressed {
if (delegate && [delegate respondToSelector:@selector(customCell: button1Pressed:)]) {
[delegate customCell:self button1Pressed:button];
}
}
你的视图控制器必须像这样采用这个协议
Your view controller must adopt this protocol like this
.h 文件
#import "MyCustomCell.h"
@interface MyViewController:UIViewController <MyCustomCellDelegate>
.....
.....
@end
在 cellForRow 的 .m 文件中:您需要将属性委托添加到单元格的方法
in .m file in cellForRow: method you need add property delegate to cell
cell.delegate = self;
最后你实现了协议中的方法
and finally you implement the method from protocol
- (void) customCell:(MyCustomCell *)cell button1Pressed:(UIButton *)btn {
}
对不起我的英语和代码.用我的电脑写的,没有 XCODE
Sorry for my english, and code. Wrote it from my PC without XCODE
这篇关于在主视图控制器的自定义单元格中使用来自 UIButton 的 IBAction的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在主视图控制器的自定义单元格中使用来自 UIButton 的 IBAction
基础教程推荐
- 突出显示朗读文本(在 iPhone 的故事书类型应用程序中) 2022-01-01
- 在 appComponent dagger 2 中动态添加测试模块? 2022-01-01
- 新的@SystemApi 注解是什么意思,和@hide 有什么区别 2022-01-01
- 在 iOS8 中无法获得正确的键盘高度值 2022-01-01
- 我的 UIImageView 的任务 2022-01-01
- - (CGRect)convertRect:(CGRect)rect toView:(UIView *)view 如何工作 2022-01-01
- 如何将多个组件添加到 PickerView? 2022-01-01
- 可可/目标C(OSX不是iOS)从子对象访问父对象 2022-01-01
- Android:STATE_SELECTED不工作 2022-01-01
- 在 Android 模拟器中激活网络位置提供程序? 2022-01-01
