【问题标题】:Swift 2.0 UITableView Section Header scroll to top when tappedSwift 2.0 UITableView 部分标题在点击时滚动到顶部
【发布时间】:2019-06-05 09:56:16
【问题描述】:

所以我到处检查,似乎找不到我正在寻找的答案。这是我的问题:我有一个 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)
    }

}

谢谢!!

【问题讨论】:

    标签: ios swift uitableview


    【解决方案1】:

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

    【讨论】:

    • 完美运行!我做了self.tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .Top, animated: true) 并将其放在 sectionHeaderTapped 函数中。谢谢!!
    【解决方案2】:

    一个好方法是使用值为“NSNotFoud”行的IndexPath,转到该部分的顶部?

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

    【讨论】:

      猜你喜欢
      • 2012-02-15
      • 1970-01-01
      • 2016-09-04
      • 1970-01-01
      • 2019-01-21
      • 2012-04-05
      • 2010-10-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多