Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 2.0 UITableView Section Header scroll to top when tapped

So I have checked everywhere and can't seem to find the answer I'm looking for. Here is my issue: I have a UITableView with different sections in it. Each section has a header that when tapped on, it expands that section and reveals it's rows or cells. However, when you tap on the header, it expands it's section down, but it stays in it's spot. I want that section header to move to the top when clicked. Below is the example code. I hope I explained this well.

Here is the section header itself:

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

Here is the sectionHeaderTapped function:

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

}

Thanks!!

like image 484
Demonic Penguin Avatar asked Dec 18 '22 20:12

Demonic Penguin


1 Answers

You can use scrollToRowAtIndexPath(_:atScrollPosition:animated:) on the table view to scroll the first row of said section to the top position.

like image 66
Tobi Nary Avatar answered Dec 24 '22 01:12

Tobi Nary