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

查看:177
本文介绍了在主视图控制器中的自定义单元格内使用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)

推荐答案

你需要在单元格的.h文件中使用委托。
像这样声明代表

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文件中的

in .m file

@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;

最后你从协议实现方法

- (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天全站免登陆