Combine static and prototype content in a table view

前端 未结 8 1036
遇见更好的自我
遇见更好的自我 2020-11-28 23:57

Is there a way to combine static tableview cells (static content) with dynamic tableview cells (prototype content) using storyboard?

8条回答
  •  渐次进展
    2020-11-29 00:23

    Since no one has actually provided a real answer to the problem (using both static and prototype cells in the same table view), I figured I'd chime in. It can be done!

    Create your static cells as you see fit. For the sections that need a dynamic cell, if you are NOT using standard UITableViewCell type, you'll need to create your custom one in a separate Nib, otherwise you can use the standard ones. Then implement the following delegates. Basically for each of these delegates, for the static stuff we want to call super, for the dynamic, we return our values.

    First, IF you need to selectively show your dynamic section, you'll want to implement the numberOfSectionsInTableView (otherwise you can leave this delegate out):

    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        int staticSections = 1;
        int dynamicSections = 1;
        if (SOME_BOOLEAN) {
            return staticSections + dynamicSections;
        } else {
            return staticSections;
        }
    }
    

    Then, you need to implement numberOfRowsInSection:

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        if (section == 1) {
            return A_COUNT;
        } else {
            return [super tableView:tableView numberOfRowsInSection:section];
        }
    }
    

    Then, you need to implement heightForRowAtIndexPath:

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        if (indexPath.section == 1) {
            return 44.0f;
        } else {
            return [super tableView:tableView heightForRowAtIndexPath:indexPath];
        }
    }
    

    Then indentationLevelForRowAtIndexPath:

    - (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        if (indexPath.section == 1) {
            return 1; // or manually set in IB (Storyboard)
        } else {
            return [super tableView:tableView indentationLevelForRowAtIndexPath:indexPath]; // or 0
        }
    }
    

    Finally, cellForRowAtIndexPath:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        if (indexPath.section == 1) {
            SomeObject *obj = self.someArray[indexPath.row];
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DynamicCell" forIndexPath:indexPath];
            cell.textLabel.text = obj.textValue;
            return cell;
        } else {
            return [super tableView:tableView cellForRowAtIndexPath:indexPath];
        }
    }
    

提交回复
热议问题