Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UItableView with only one section sticky

I have a UITableView in which there are lot of sections. If I make the UITableView type as plain all section stick to the top while scrolling.

My requirement is to stick only header for section zero and other headers should float (like when u set the style as group).

Also Note my TableView is having the functionality of collapse and expand which I did using the sections.

My UItableView style is set to plain

public enum UITableViewStyle : Int {
    case plain // regular table view
}

I have implemented custom section header using

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? 

and

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat

Any hint in right direction is highly appreciated

like image 600
Ekra Avatar asked Nov 02 '25 19:11

Ekra


1 Answers

There is a tricky solution to this situation. I have tried to write the solution in Swift but for now i am unable to find the solution but i have achieved the above solution in Objective-C.

You need to subclass UITableView and expose the private api and override them so you can achieve what you want.

Below is an example TableView.

MYTableView.h

@interface MYTableView : UITableView
@property (assign,nonatomic)BOOL shouldFloatHeader;
@property (assign,nonatomic)BOOL shouldFloatFooter;
- (BOOL)allowsHeaderViewsToFloat;
- (BOOL)allowsFooterViewsToFloat;
@end

MYTableView.m

@implementation MYTableView
- (BOOL)allowsHeaderViewsToFloat{
    return _ shouldFloatHeader;
}
- (BOOL)allowsFooterViewsToFloat{
    return shouldFloatFooter;
}
@end

Now you can use above TableView in swift as well. I have run and tested it.

Now to make first section sticky and all others non sticky we need to have some trick here. Below is an illustration. There is UITableViewDelegate method didEndDisplayingHeader just implement this method and made toggle shouldFloatHeader like this..

Objective-C

-(void)tableView:(MYTableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section {
    if (section >= 1) {
        tableView.shouldFloatHeader = YES;
    }else {
        tableView.shouldFloatHeader = NO;
    }
}

Swift

func tableView(_ tableView: MYTableView, didEndDisplayingHeaderView view: UIView, forSection section: Int) {
        if section >= 1 {
            tableView.shouldFloatHeader = true
        }else {
            tableView.shouldFloatHeader = false
        }
    }

Using private API's can lead your application to reject in some cases.

like image 84
Syed Qamar Abbas Avatar answered Nov 04 '25 11:11

Syed Qamar Abbas