Objective C中的UITableViewController是什么?

我想请教一下,Objective C中的UITableViewController是什么?我正在学习Objective C,但我并不是很理解UITableViewController的用途和作用。我知道它是一个视图控制器,并且用于管理表格视图,但是除此之外,还有哪些具体的应用场景和实现方法?有没有哪位大神能提供一些详细的解释和代码示例呢?非常感谢!

提问时间:2023-07-04 16:52:42 编辑时间:2023-07-04 16:52:44 提问者: Starlit_Serenade
  • Blue_Sapphire
    3

    UITableViewController是一个预定义的视图控制器,在iOS中用于显示表格视图。它提供了许多有用的功能,例如轻松实现数据源方法、自动管理滚动行为、处理行选择等等。使用它,您可以更快地创建表格视图,并且更容易地将它们与其他操作结合使用。常见的实现方法是子类化UITableViewController,实现必要的数据源方法和其他适用的委托方法,然后将控制器分配给表格视图。以下是一个基本的UITableViewController实现示例:

    @interface MyTableViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>
    
    @end
    
    @implementation MyTableViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        //设置表格视图数据源
        self.tableView.dataSource = self;
        //设置表格视图委托
        self.tableView.delegate = self;
    }
    
    #pragma mark - Table view data source
    
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
        return 1;
    }
    
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        return 10;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }
        cell.textLabel.text = [NSString stringWithFormat:@"Row %ld", indexPath.row];
        return cell;
    }
    
    #pragma mark - Table view delegate
    
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        NSLog(@"Selected row: %ld", indexPath.row);
    }
    
    @end
    
    回答时间:2023-07-04 16:52:47