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
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.
@interface MYTableView : UITableView
@property (assign,nonatomic)BOOL shouldFloatHeader;
@property (assign,nonatomic)BOOL shouldFloatFooter;
- (BOOL)allowsHeaderViewsToFloat;
- (BOOL)allowsFooterViewsToFloat;
@end
@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..
-(void)tableView:(MYTableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section {
if (section >= 1) {
tableView.shouldFloatHeader = YES;
}else {
tableView.shouldFloatHeader = NO;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With