【问题标题】:How to add sections to a UITableView?如何将部分添加到 UITableView?
【发布时间】:2013-04-25 03:11:40
【问题描述】:

有人可以用基本术语解释一下添加部分的流程是如何工作的吗?

我有一组对象,我目前正在将它们填充到单个分段UITableView 中,但是我想根据这些对象的共享“类别”属性将它们分成多个部分。我从 API 获取对象列表,所以我事先不知道每个类别有多少。

非常感谢。

【问题讨论】:

    标签: ios objective-c uitableview cocoa-touch uikit


    【解决方案1】:

    您必须使用 UITableViewDataSource 协议。您必须实现其中一种可选方法:

    //Optional
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        // Default is 1 if not implemented
    
        NSUInteger sectionCount = 5; //Or whatever your sections are counted as...
        return sectionCount;
    }
    

    确保随后计算每个部分的行数:

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return 4;  //This will return 4 rows in each section
    }
    

    如果您想为每个部分命名页眉和页脚:

    - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
    {
        return @"";
    }// fixed font style. use custom view (UILabel) if you want something different
    
    - (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
    {
        return @"";
    }
    

    最后,确保正确实现单元格:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        // Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
        // Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
    
        NSUInteger section = [indexPath indexAtPosition:0];
        NSUInteger rowInSection = [indexPath indexAtPosition:1];
    
        //Do your logic goodness here grabbing the data and creating a reusable cell
    
        return nil;  //We would make a cell and return it here, which corresponds to that section and row.
    }
    

    可折叠部分完全是另一种野兽。你需要继承 UITableView,或者只是在 CocoaControls 上找到一个。

    【讨论】:

    • 感谢您的发帖!在返回单元格之前如何指定单元格所在的部分?
    • tableview:cellForRowAtIndexPath: 基本上要求您提供表格视图的第 x 行 y 部分中的单元格。请注意我是如何将部分和行从索引路径中拉出的。
    猜你喜欢
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    相关资源
    最近更新 更多