Demonic Penguin
Demonic Penguin

Reputation: 43

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!!

Upvotes: 4

Views: 8934

Answers (2)

gugapc
gugapc

Reputation: 224

One good way is to use IndexPath with a value of row "NSNotFoud", to go to the top of the section 😁

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

Upvotes: 6

Tobi Nary
Tobi Nary

Reputation: 4596

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

Upvotes: 6

Related Questions