在主视图控制器的自定义单元格中使用来自 UIButton 的 IBAction [英] Use IBAction from UIButton inside custom cell in main view controller

查看:16
本文介绍了在主视图控制器的自定义单元格中使用来自 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆