2012-06-26 66 views

回答

8

如果該部分的第一個單元格不再可見,則標題將會浮動。所以:

NSIndexPath *topCellPath = [[self.tableView indexPathsForVisibleRows] objectAtIndex:0]; 
if (topCellPath.row != 0) 
{ 
    // Header must be floating! 
} 

您可以通過滾動與scrollToRowAtIndexPath:atScrollPosition:animated:指數路徑和UITableViewScrollPositionNone滾動位置達到類似的效果 - 這不會滾動,如果在一節中的第一個單元格已經在屏幕上。

+1

謝謝,這作品!使用'scrollToRowAtIndexPath:atScrollPosition:animated:'不適用於我的情況,因爲該部分可能會摺疊並因此不包含一行。 – Meinhard

+0

@meinhard是否在使用https://github.com/rob-nash/CollapsableTable? – 2017-06-16 09:28:19

1

您可以先存儲節頭視圖的原始矩形。

headerView.originalPoint = [tableView rectForHeaderInSection:section].origin; 

併發送scrollViewDidScroll:scrollView消息到標題。

在你的頭視圖

- (void)scrollViewDidScroll:(UIScrollView *)scrollView { 
    BOOL isFloating = self.frame.origin.y > self.originalPoint.y; 
    if (isFloating) { 
     //DO what you want 
    } 
} 
1

這工作。

@implementation UITableView (rrn_extensions) 

-(BOOL)rrn_isFloatingSectionHeaderView:(UITableViewHeaderFooterView *)view { 
    NSNumber *section = [self rrn_sectionForHeaderFooterView:view]; 
    return [self rrn_isFloatingHeaderInSection:section.integerValue]; 
} 

-(BOOL)rrn_isFloatingHeaderInSection:(NSInteger)section { 
    CGRect frame = [self rectForHeaderInSection:section]; 
    CGFloat y = self.contentInset.top + self.contentOffset.y; 
    return y > frame.origin.y; 
} 

-(NSNumber *)rrn_sectionForHeaderFooterView:(UITableViewHeaderFooterView *)view { 
    for (NSInteger i = 0; i < [self numberOfSections]; i++) { 
     CGPoint a = [self convertPoint:CGPointZero fromView:[self headerViewForSection:i]]; 
     CGPoint b = [self convertPoint:CGPointZero fromView:view]; 
     if (a.y == b.y) { 
      return @(i); 
     } 
    } 
    return nil; 
} 

@end 
0

該代碼適用於我。

- (BOOL)isSection0HeaderSticky { 
    CGRect originalFrame = [self.listTableView rectForHeaderInSection:0]; 

    UIView *section0 = [self.listTableView headerViewForSection:0]; 

    if (originalFrame.origin.y < section0.frame.origin.y) { 
     return YES; 
    } 
    return NO; 
} 
0

添加@ robdashnash的回答迅速端口

extension UITableView 
{ 
    func isFloatingSectionHeader(view:UITableViewHeaderFooterView)->Bool 
    { 
      if let section = section(for:view) 
      { 
       return isFloatingHeaderInSection(section:section) 
      } 
      return false 
     } 

    func isFloatingHeaderInSection(section:Int)->Bool 
    { 
     let frame = rectForHeader(inSection:section) 
     let y = contentInset.top + contentOffset.y 
     return y > frame.origin.y 
    } 

    func section(for view:UITableViewHeaderFooterView)->Int? 
    { 
     for i in stride(from:0, to:numberOfSections, by:1) 
     { 
      let a = convert(CGPoint.zero, from:headerView(forSection:i)) 
      let b = convert(CGPoint.zero, from:view) 
      if a.y == b.y 
      { 
       return i 
      } 
     } 
     return nil 
    } 
}