objective-c 将 UITableview 数据源和委托与主 UIViewController 类分开的简单方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2097864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 22:48:20  来源:igfitidea点击:

Simple way to separate UITableview datasource and delegate from main UIViewController class?

iphoneobjective-cxcode

提问by Alexi Groove

The typical UITableView usage pattern is to have the main UIViewController become a target datasource and delegate for the UITableView it is holding on to.

典型的 UITableView 使用模式是让主 UIViewController 成为它所持有的 UITableView 的目标数据源和委托。

Are there any simple and easy to follow tutorials that would help me figure out how to move the code that pertains to the UITableViewDelegate and UITableViewDataSource methods into a separate class and hook that to my UIViewController instead? I would ideally like to have both the delegate and datasource living in the same class.

是否有任何简单易学的教程可以帮助我弄清楚如何将与 UITableViewDelegate 和 UITableViewDataSource 方法相关的代码移动到一个单独的类中,并将其挂接到我的 UIViewController 上?理想情况下,我希望委托和数据源都在同一个类中。

Right now, I am creating the UITableView via Interface Builder and connecting its outlet to my controller class.

现在,我正在通过 Interface Builder 创建 UITableView 并将其插座连接到我的控制器类。

Typical code:

典型代码:

@interface MyController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
    IBOutlet UITableview *myTableview;
}

I want to do something more like this:

我想做更多这样的事情:

@interface MyController : UIViewController 
{
    IBOutlet UITableview *myTableview;
}
@end

@interface MyTableSourceDelegate : NSObject<UITableViewDelegate, UITableViewDataSource>
{
}

@implementation MyTableSourceDelegate
    // implement all of the UITableViewDelegate and methods in this class 
@end

回答by WINSergey

I spend 2 hours to solve this problem:

我花了2个小时来解决这个问题:

It's working for me

它对我有用

//  GenreDataSource.h

#import Foundation/Foundation.h

    @interface GenreDataSource : NSObject <UITableViewDataSource> {
        NSArray *dataSource;
        CGSize cellSize;
    }

@property(nonatomic, assign) CGSize cellSize;

@end



//  GenreDataSource.m
#import "GenreDataSource.h"

@implementation GenreDataSource
@synthesize cellSize;

-(id)init{

    self = [super init];
    if ( self != nil ) {

        dataSource = [[NSArray alloc] initWithObjects:@"All",@"Folk",@"Disco",@"Blues",@"Rock",@"Dance",@"Hip-Hop",@"R&B",@"Soul",@"Lounge",@"Techno",@"Bubstep", nil];
    }
    return self;
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [dataSource count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"CellPicker";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {

        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero] autorelease];
        [cell setSelectionStyle:UITableViewCellSelectionStyleGray];

        //сконфигурируем структуру
        FontLabel *fLabel= [[FontLabel alloc] initWithFrame:CGRectMake(30, 
                                                                       5, 
                                                                       cellSize.width-30, 
                                                                       cellSize.height-5)
                                                   fontName:@"HelveticaNeueCondensedBlack" 
                                                  pointSize:18.0f];
        [fLabel setTextColor:[UIColor darkTextColor]];
        [fLabel setTag:101];
        [fLabel setBackgroundColor:[UIColor clearColor]];
        [cell.contentView addSubview:fLabel];
        [fLabel release];
    }

    FontLabel *fLabel = (FontLabel*)[cell viewWithTag:101];
    [fLabel setText:[dataSource objectAtIndex:indexPath.row]];

    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

@end

回答by smileBot

Firstthing is if you're using a UITableViewController subclass with interface builder you will want to disconnect the delegate and datasource outlets that are already hooked up by default. (Hint, look in the connections inspector). Check even if you have a tableView inside a viewController.

第一件事是,如果您使用 UITableViewController 子类和界面构建器,您将希望断开默认情况下已经连接的委托和数据源出口。(提示,查看连接检查器)。即使您在viewController中有一个tableView,也要检查。

Secondcreate your classes and make sure they conform to <UITableViewDelegate>and <UITableViewDataSource>. You're probably going to have to declare this contract in the .h file if you're using objc.

其次创建您的类并确保它们符合<UITableViewDelegate><UITableViewDataSource>。如果您使用的是 objc,您可能必须在 .h 文件中声明此合同。

Third, In your view controller instantiate this class or two separate classes somewhere like viewDidLoad, and then assign self.tableView.delegate = myCustomDelegateInstanceand self.tableView.dataSource = myCustomDataSourceInstance.

第三,在你的视图控制器中实例化这个类或两个单独的类viewDidLoad,然后分配self.tableView.delegate = myCustomDelegateInstanceself.tableView.dataSource = myCustomDataSourceInstance

Now, any calls that come through the controller will be dispatched to your custom handlers. Pretty basic.

现在,来自控制器的任何调用都将被分派到您的自定义处理程序。很基本。

The only reason to really do this is if you 1) have a very bloated controller, or 2) you need to reuse the dataSource and delegate methods somewhere else and you want to avoid code repetition. Otherwise, it's probably better practice to leave it put.

真正这样做的唯一原因是,如果您 1) 有一个非常臃肿的控制器,或者 2) 您需要在其他地方重用 dataSource 和委托方法,并且您想避免代码重复。否则,最好将其搁置。

回答by CiNN

You can create separe classes (with UITableViewDelegate , UITableViewDataSource) and add them in IB as external files and link the IBActions

您可以创建单独的类(使用 UITableViewDelegate ,UITableViewDataSource)并将它们作为外部文件添加到 IB 中并链接 IBActions

回答by shawnwall

In IB, you can drag a 'External Object' from Library->Cocoa Touch->Controllers into your xib window. You can then select that object, view the inspector, and set the class. It is now available to serve as a delegate, etc.

在 IB 中,您可以将“外部对象”从 Library->Cocoa Touch->Controllers 拖到您的 xib 窗口中。然后,您可以选择该对象、查看检查器并设置类。现在可以用作代表等。