Swift 2.0 UITableView Section Header在点击时滚动到顶部

时间:2016-01-13 16:18:42

标签: ios swift uitableview

所以我到处检查,似乎无法找到我正在寻找的答案。这是我的问题:我有一个UITableView,里面有不同的部分。每个部分都有一个标题,当点击时,它会扩展该部分并显示它的行或单元格。但是,当你点击标题时,它会向下扩展它的部分,但它会保留在它的位置。我希望该部分标题在单击时移动到顶部。下面是示例代码。我希望我能很好地解释这一点。

以下是节标题:

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)
    }

}

谢谢!

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:0)

一种好方法是使用索引值为“ NSNotFoud”行的IndexPath,转到?部分的顶部。

    let indexPath = IndexPath(row: NSNotFound, section: 0)
    self.scrollToRow(at: indexPath, at: .top, animated: true)