2016-01-13 141 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