iOS可以将所有委托方法放在另一个类上。将代理继承到视图控制器 [英] iOS Can I put all delegate method on another class. Inherit the delegates into a view controller

查看:116
本文介绍了iOS可以将所有委托方法放在另一个类上。将代理继承到视图控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要的是将我所有的委托方法集中到一个类中。我可以使用其默认值或覆盖委托方法。

What I want is to centralize all my delegate methods into a class. Where I can either use its defaults or override the delegate method.

例如:

ViewController.m

ViewController.m

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>

@end

ViewController.h

ViewController.h

#import "ViewController.h"
#import "TableDelegateContainers.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

TableDelegateContainers.h

TableDelegateContainers.h

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return sample.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    return cell;
}

基本上所有的UITableViewDataSource所需的委托方法都将放在另一个类中。当我将该类导入到ViewController.h中时,将使用这些方法。如果我想,我可以覆盖它们。

Basically all the delegate methods that the UITableViewDataSource need will be put to another class. And when I import that class to thew ViewController.h those methods will be used. And I can either overwrite them if I want to.

这可以通过课程实现吗?或者其他实体需要?

Is this achievable by class? Or other entity is needed?

推荐答案

我想他想将代理方法提取到一个单独的类中。所以创建一个自定义类:

I think he wants to extract the delegate methods into a separate class. so create a custom class:

TableViewHelper.h

TableViewHelper.h

@interface TableViewHelper : NSObject<UITableViewDataSource,UITableViewDelegate>
- (id) initWithTableView: (UITableView *) tableView;
@end

TableViewHelper.m

TableViewHelper.m

@implementation TableViewHelper

- (id) initWithTableView: (UITableView *) tableView {
    self = [super init];
    if (self) {
        tableView.datasource = self;
        tableView.delegate = self;
    }
    return self;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return sample.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    return cell;
}
@end

ViewController.m

ViewController.m

@interface ViewController ()
@property (nonatomic, strong) TableViewHelper *tvHelper;
@end

@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.tvHelper = [[TableViewHelper alloc] initWithTableView: self.tableView];
    // Do any additional setup after loading the view, typically from a nib.
}
@end

所以你的ViewController不需要实现两个协议

so your ViewController does not need to implement both protocols anymore.

这篇关于iOS可以将所有委托方法放在另一个类上。将代理继承到视图控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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