iOS开发 oc 如何自定义cell中写点击事件的block

123 阅读1分钟

在iOS开发中,使用Block来处理自定义UITableViewCell上的按钮点击事件是一种简洁且高效的方法。以下是详细的步骤和代码示例,基于我搜索到的资料进行整理:

1. 在自定义Cell的.h文件中声明Block和Block属性

首先,在自定义的UITableViewCell子类的头文件中声明一个Block类型,并添加一个Block属性。例如:

// CustomTableViewCell.h

#import <UIKit/UIKit.h>

typedef void (^ButtonClick)(UIButton *sender);

@interface CustomTableViewCell : UITableViewCell

@property (nonatomic, strong) UIButton *customButton;

@property (nonatomic, copy) ButtonClick buttonClickBlock;

@end

2. 在自定义Cell的.m文件中设置按钮点击事件

在自定义的UITableViewCell子类的实现文件中,为按钮添加点击事件,并在点击事件中调用Block。例如:

// CustomTableViewCell.m

#import "CustomTableViewCell.h"

@implementation CustomTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {

self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];

if (self) {

_customButton = [UIButton buttonWithType:UIButtonTypeSystem];

[_customButton setTitle:@"点击我" forState:UIControlStateNormal];

[_customButton addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];

[self.contentView addSubview:_customButton];

// 设置按钮的约束或frame

_customButton.translatesAutoresizingMaskIntoConstraints = NO;

[NSLayoutConstraint activateConstraints:@[

[_customButton.centerXAnchor constraintEqualToAnchor:self.contentView.centerXAnchor],

[_customButton.centerYAnchor constraintEqualToAnchor:self.contentView.centerYAnchor]

]];

}

return self;

}

- (void)buttonTapped:(UIButton *)sender {

if (self.buttonClickBlock) {

self.buttonClickBlock(sender);

}

}

@end

3. 在ViewController中设置Block

在ViewController中,当配置cell时,设置cell的Block属性。例如:

// ViewController.m

#import "ViewController.h"

#import "CustomTableViewCell.h"

@interface ViewController () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];

self.tableView.dataSource = self;

self.tableView.delegate = self;

[self.view addSubview:self.tableView];

[self.tableView registerClass:[CustomTableViewCell class] forCellReuseIdentifier:@"CustomCellIdentifier"];

}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

return 20; // 假设有20行

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomCellIdentifier" forIndexPath:indexPath];

cell.buttonClickBlock = ^(UIButton *sender) {

NSLog(@"Button in cell %ld was tapped", (long)indexPath.row);

// 在这里处理点击事件,例如跳转到新的视图控制器

};

return cell;

}

@end

总结

通过上述步骤,你可以在自定义的UITableViewCell中使用Block来处理按钮点击事件。这种方法不仅简化了代码,还提高了代码的可读性和可维护性。在实际开发中,你可以根据具体需求调整Block的参数和实现逻辑。