2016-01-13 140 views
2

所以我已经到处检查,似乎无法找到我正在寻找的答案。这是我的问题:我有一个UITableView与其中的不同部分。每个部分都有一个标题,当点击时,它会展开该部分并显示它的行或单元格。但是,当您点击标题时,它会展开它的部分,但它保持在它的位置。点击时,我希望该部分标题移动到顶部。以下是示例代码。我希望我解释得很好。Swift 2.0 UITableView Section Header点击滚动到顶部

这里是节头本身:

func configureHeader(view: UIView, section: Int) { 

    view.backgroundColor = UIColor.whiteColor() 
    view.tag = section 

    let headerString = UILabel(frame: CGRect(x: 40, y: 15, width: tableView.frame.size.width-10, height: 40)) as UILabel 
    headerString.text = sectionTitleArray.objectAtIndex(section) as? String 
    headerString.textAlignment = .Left 
    headerString.font = UIFont.systemFontOfSize(24.0) 
    view .addSubview(headerString) 

    let frame = CGRectMake(5, view.frame.size.height/2, 20, 20) 
    let headerPicView = UIImageView(frame: frame) 
    headerPicView.image = headerPic 
    view.addSubview(headerPicView) 

    let headerTapped = UITapGestureRecognizer (target: self, action:"sectionHeaderTapped:") 
    view .addGestureRecognizer(headerTapped) 
} 

这里是sectionHeaderTapped功能:

func sectionHeaderTapped(recognizer: UITapGestureRecognizer) { 
    print("Tapping working") 
    print(recognizer.view?.tag) 

    let indexPath : NSIndexPath = NSIndexPath(forRow: 0, inSection:(recognizer.view?.tag as Int!)!) 
    if (indexPath.row == 0) { 

     var collapsed = arrayForBool .objectAtIndex(indexPath.section).boolValue 
     collapsed  = !collapsed; 

     arrayForBool .replaceObjectAtIndex(indexPath.section, withObject: collapsed) 
     //reload specific section animated 
     let range = NSMakeRange(indexPath.section, 1) 
     let sectionToReload = NSIndexSet(indexesInRange: range) 
     self.tableView .reloadSections(sectionToReload, withRowAnimation:UITableViewRowAnimation.Fade) 
    } 

} 

谢谢!

回答

5

您可以在表视图上使用scrollToRowAtIndexPath(_:atScrollPosition:animated:)将上述部分的第一行滚动到顶部位置。

+1

工作完美!我做了'self.tableView.scrollToRowAtIndexPath(indexPath,atScrollPosition:.Top,animated:true)',并把它放在sectionHeaderTapped函数中。谢谢!! –

+0

完成了很好的工作,谢谢 – Gaurav