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


基础教程推荐
- iOS4 创建后台定时器 2022-01-01
- NSString intValue 不能用于检索电话号码 2022-01-01
- Cocos2d iPhone 非矩形精灵触摸检测 2022-01-01
- Android:getLastKnownLocation(LocationManager.NETWORK_PROVIDER 2022-01-01
- 如何从 logcat 中删除旧数据? 2022-01-01
- navigator.geolocation.getCurrentPosition 在 Android 浏览器上 2022-01-01
- iPhone - 获取给定地点/时区的当前日期和时间并将其与同一地点的另一个日期/时间进行比较的正确方法 2022-01-01
- libGDX 从精灵或纹理中获取像素颜色 2022-01-01
- AdMob 广告未在模拟器中显示 2022-01-01
- 通过重定向链接在 Google Play 中打开应用 2022-01-01