【问题标题】:It is possible to have numberOfSectionsInTableView dynamically?可以动态地拥有 numberOfSectionsInTableView 吗?
【发布时间】:2011-11-10 16:16:50
【问题描述】:

我可以动态获得行数吗? 我正在尝试删除 tableView 部分标题,但我不知道如何......我已经教过一个解决方案是更改部分的数量。

现在我的 numberOfSectionsInTableView 看起来像:

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

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    beTribesAppDelegate *appDelegate = [UIApplication sharedApplication].delegate;

    switch (section) {
        case 0:
            return [appDelegate.firstArray count];
        case 1:
            return [appDelegate.secondArray count];    
        default:
            return 0;
    }
}

像这样设置标题部分:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{ 
    sectionTitles = [[NSMutableArray alloc] init];

        [sectionTitles addObject:@"firstSection"];
        [sectionTitles addObject:@"secondSection"];
    NSString *sectionText = [sectionTitles objectAtIndex:section];
    return sectionText;
}

【问题讨论】:

    标签: iphone uitableview ios5 tableview


    【解决方案1】:

    我不确定是否理解这个问题,因为答案似乎微不足道:只需更改实现以返回一些动态值就可以了,对吧?

    -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
        return self.nbSections;
    }
    

    其中nbSections 是一个属性,您将为其分配所需的值,以便您可以随时更改它。那到底是怎么回事?

    PS:当然,请致电[tableView reloadData] 重新计算您的 tableView 的内容并明显考虑新值...也许这就是您所缺少的?

    【讨论】:

    • 还有一个……我不知道该放在哪里[tableView reloadData]
    • 在您更改 nbSections 的值之后。阅读 Apple 文档中的“表格视图编程指南”,它通过示例代码和关于表格视图、部分、单元格等的通用原则进行了解释
    • 那我应该把它放在numberOfSectionsInTableView方法里面?
    • 没有。调用realoadData 会触发对该方法的调用的东西。当您计划在代码中编写nbSections = ... 时放置它。真的,去阅读文档。
    • 好吧,我虽然设置到位,像这样:AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; if (appDelegate.firstArray.count == 0) { numberOfSections = 1; } else { numberOfSections = 2; }
    【解决方案2】:

    要删除部分标题,您必须像这样将标题高度设置为 0

    - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
        switch (section) {
            case 0:
                return 0;
            default:
                return 44;
        }
    }
    

    此示例将删除第一个部分标题,所有其他部分将设置为 44。

    【讨论】:

      【解决方案3】:

      首先要做的是将 sectionTitles 数组移动到视图控制器上的一个属性中,并在您的 init 方法中对其进行初始化。

      然后当你想改变一个节的标题时,改变数组中的值并调用[tableView reloadData]

      你想从 tableView 中删除整个部分还是只删除标题?如果您只想删除标头,请将数组中的项目设置为 @""

      如果您想完全删除该部分,请从 sectionTitles 中删除该项目并将您的 numberOfSectionsInTableView 方法更改为:

      -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
              return [sectionTitles count];
      }
      

      【讨论】:

        猜你喜欢
        • 2018-07-30
        • 2018-11-05
        • 2018-02-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多