if we click on Custom Section Header in UITableView, then move that section to top

后端 未结 2 775
心在旅途
心在旅途 2021-02-04 16:59

I have a Custom Section Header in UITableView, on that section header there placed UIButton on its very right.What i want is, if i click o

2条回答
  •  遥遥无期
    2021-02-04 17:41

    Step 1: set the size of Section header. Example as follows.

    - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
        return 55;
    }
    

    Step 2: create & return the customized section header.

    - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
        UIView *aView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 55)];
        UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
        [btn setFrame:CGRectMake(0, 0, 320, 55)];
        [btn setTag:section+1];
        [aView addSubview:btn];
        [btn addTarget:self action:@selector(sectionTapped:) forControlEvents:UIControlEventTouchDown];
        return aView;
    }
    

    Step 3: return number of sections. ( for example 10 here )

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

    Step 4 : number of rows per section. ( for example, 4 rows for each section )

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return 4;
    }
    

    Step 5 : create & return cell (UITableViewCell for each Row)

    - (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.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        cell.textLabel.text=[NSString stringWithFormat:@"%i_%i",indexPath.section,indexPath.row];
    
        return cell;
    }
    

    Step 6: add the event to handle the TouchDown on section header.

    - (void)sectionTapped:(UIButton*)btn {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:btn.tag-1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
    

提交回复
热议问题