美文网首页
iOS Objective-C Xib, 新增TableView

iOS Objective-C Xib, 新增TableView

作者: 不要虚度美好的时光 | 来源:发表于2023-02-18 23:29 被阅读0次

如果您想在iOS Objective-C的Xib中添加UITableView,可以按照以下步骤进行操作:

  1. 在Xib文件中,从Object Library中选择一个UITableView并将其拖动到您希望添加UITableView的位置。
  2. 在您的ViewController.h文件中添加UITableViewDelegate和UITableViewDataSource协议。
  3. 在您的ViewController.m文件中添加以下代码:
@interface ViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 设置tableview的delegate和dataSource为当前controller
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
}

#pragma mark - UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1; // 如果你只有一个section, 可以返回1
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 10; // 返回你想要显示的行数
}

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

@end

上面的代码创建了一个UITableView,并将它的delegate和dataSource设置为当前的ViewController。然后,它实现了UITableViewDelegate和UITableViewDataSource协议中的必要方法,包括numberOfSectionsInTableView,numberOfRowsInSection和cellForRowAtIndexPath。在cellForRowAtIndexPath方法中,它创建了一个UITableViewCell并返回它,同时将一些示例文本添加到单元格中。在实际应用中,您将需要使用您自己的数据和自定义单元格。

请注意,还需要将UITableView对象与视图控制器的IBOutlet进行连接,以便能够在代码中访问它。在上面的代码中,我们将UITableView对象与名为“tableView”的IBOutlet连接在一起。

相关文章

网友评论

      本文标题:iOS Objective-C Xib, 新增TableView

      本文链接:https://www.haomeiwen.com/subject/kuxikdtx.html