跳到主要内容

给出委托方法的实例,并且说出UITableVIew的Data Source方法?

参考答案:

在iOS开发中,委托(delegate)是一种设计模式,它允许一个对象(委托者)将其某些责任(或任务)委托给另一个对象(被委托者)。这通常用于在不同对象之间建立松散的耦合关系,使得代码更加灵活和可维护。

委托方法的实例

假设我们有一个名为CustomView的自定义视图,它需要在某个事件发生时通知外部对象。我们可以使用委托模式来实现这一功能。

首先,在CustomView.h中定义委托协议:

@protocol CustomViewDelegate <NSObject>
- (void)customViewDidTap:(CustomView *)customView;
@end

@interface CustomView : UIView
@property (nonatomic, weak) id<CustomViewDelegate> delegate;
@end

然后,在CustomView.m中触发委托方法:

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if ([self.delegate respondsToSelector:@selector(customViewDidTap:)]) {
        [self.delegate customViewDidTap:self];
    }
}

最后,在外部使用CustomView的类中,实现委托协议:

@interface ViewController () <CustomViewDelegate>
@property (nonatomic, strong) CustomView *customView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.customView = [[CustomView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    self.customView.delegate = self;
    [self.view addSubview:self.customView];
}

- (void)customViewDidTap:(CustomView *)customView {
    NSLog(@"Custom view was tapped!");
}

@end

在这个例子中,当CustomView被点击时,它会调用其委托的customViewDidTap:方法。ViewController作为CustomView的委托,实现了这个方法,并在控制台输出一条消息。

UITableView的Data Source方法

UITableView是iOS中用于展示列表数据的控件。它使用数据源(data source)和委托(delegate)来管理数据和用户交互。数据源提供表格视图所需的数据,而委托处理用户交互事件。

UITableViewDataSource协议定义了以下一些常用的数据源方法:

  1. numberOfSectionsInTableView: 返回表格视图中分区的数量。
  2. tableView:numberOfRowsInSection: 返回指定分区中的行数。
  3. tableView:cellForRowAtIndexPath: 为指定的索引路径返回或创建一个表格单元格。

例如:

@interface ViewController () <UITableViewDataSource>
@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.view addSubview:self.tableView];
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 10; // 假设有10行数据
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"Row %ld", (long)indexPath.row];
    return cell;
}

@end

在这个例子中,ViewController作为UITableView的数据源,提供了表格视图所需的数据。numberOfSectionsInTableView:返回1,表示有一个分区;tableView:numberOfRowsInSection:返回10,表示每个分区有10行;tableView:cellForRowAtIndexPath:为每行返回一个表格单元格,并设置其文本标签的内容。