Swift   发布时间:2022-03-31  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何实现可收起和展开的Table Section大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_944_0@

概述

如何实现可收起和展开的Table Section 这是一个简单的iOS swift项目,旨在介绍如何实现可收起和展开的table section,并且,项目不需要main storyboard, XIB, 注册nib等,只需要纯的Swfit代码! 项目源代码:https://github.com/jeantimex/ios-swift-collapsible-table-section 如果你希望

如何实现可收起和展开的Table Section

这是一个简单的iOS swift项目,旨在介绍如何实现可收起和展开的table section,并且,项目不需要main storyboard,XIB,注册nib等,只需要纯的Swfit代码

项目源代码https://github.com/jeantimex/ios-swift-collapsible-table-section

如果你希望获得Swift 3.0的代码,可以在migrate-to-swift-3.0分支里找到,最终将会汇入master分支。

效果


如何实现可收起和展开的Table Section?

第一步. 准备数据

假设我们有如下的数据,它已经按照不同的section进行组织和整理,每个section都是一个Section结构(或对象):

struct Section {
  var name: String!
  var items: [String]!
  var collapsed: Bool!

  init(name: String,items: [String],collapsed: Bool = falsE) {
    self.name = name
    self.items = items
    self.collapsed = collapsed
  }
}

var sections = [Section]()

sections = [
  Section(name: "Mac",items: ["MACBook","MACBook Air","MACBook Pro","iMac","Mac Pro","Mac mini","Accessories","OS X El Capitan"]),Section(name: "iPad",items: ["iPad Pro","iPad Air 2","iPad mini 4","Accessories"]),Section(name: "iPhone",items: ["iPhone 6s","iPhone 6","iPhone SE","Accessories"])
]

collapsed表示当前的section是否被收起或展开,认下是false,即展开。

第二步. Section Header

根据苹果 API reference,我们应该使用UITableViewHeaderFooterView. 让我们创一个section header的类来继承它,我们把这个section header类起名为CollapsibleTableViewHeader:

class CollapsibleTableViewHeader: UITableViewHeaderFooterView {
    let titleLabel = UILabel()
    let arrowLabel = UILabel()

    override init(reusEIDentifier: String?) {
        super.init(reusEIDentifier: reusEIDentifier)

        contentView.addSubview(titleLabel)
        contentView.addSubview(arrowLabel)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

用户点击section header的时候我们需要收起或者展开这个section,为了实现这样的效果,让我们借用一下UITapGestureRecognizer. 同时我们需要将这个tap事件通知给table view并让它来更新section的collapsed值。

protocol CollapsibleTableViewHeaderDelegate {
    func toggleSection(header: CollapsibleTableViewHeader,section: int)
}

class CollapsibleTableViewHeader: UITableViewHeaderFooterView {
    var delegate: CollapsibleTableViewHeaderDelegate?
    var section: Int = 0
    ...
    override init(reusEIDentifier: String?) {
        super.init(reusEIDentifier: reusEIDentifier)
        ...
        addGestureRecognizer(UITapGestureRecognizer(target: self,action: #SELEctor(CollapsibleTableViewHeader.tapHeader(_:))))
    }
    ...
    func tapHeader(gestureRecognizer: UITapGestureRecognizer) {
        guard let cell = gestureRecognizer.view as? CollapsibleTableViewHeader else {
            return
        }
        delegate?.toggleSection(self,section: cell.section)
    }

    func setCollapsed(collapsed: Bool) {
        // Animate the arrow rotation (see Extensions.swf)
        arrowLabel.rotate(collapsed ? 0.0 : CGFloat(M_PI_2))
    }
}

既然我们不用任何storyboard或者XIB,如何实现自动布局呢?答案是运用NSLayoutConsTraintconsTraintsWithVisualFormat函数

override init(reusEIDentifier: String?) {
    ...
    // arrowLabel must have fixed width and height
    arrowLabel.widthAnchor.consTraintEqualToConstant(12).active = true
    arrowLabel.heightAnchor.consTraintEqualToConstant(12).active = true

    titleLabel.translatesAutoresizingMaskIntoConsTraints = false
    arrowLabel.translatesAutoresizingMaskIntoConsTraints = false
}

override func layoutSubviews() {
    super.layoutSubviews()
    ...
    let views = [
        "titleLabel" : titleLabel,"arrowLabel" : arrowLabel,]

    contentView.addConsTraints(NSLayoutConsTraint.consTraintsWithVisualFormat(
        "H:|-20-[titleLabel]-[arrowLabel]-20-|",options: [],metrics: nil,views: views
    ))

    contentView.addConsTraints(NSLayoutConsTraint.consTraintsWithVisualFormat(
        "V:|-[titleLabel]-|",views: views
    ))

    contentView.addConsTraints(NSLayoutConsTraint.consTraintsWithVisualFormat(
        "V:|-[arrowLabel]-|",views: views
    ))
}

第三步. UITableView Datasource 以及 Delegate

首先,sections的数量sections.count:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
  return sections.count
}

每个section里面cell的数量为:

override func tableView(tableView: UITableView,numberOfRowsInSection section: int) -> Int {
    return sections[section].items.count
}

接下来使用tableView的viewForHeaderInSection函数来渲染我们的section header:

override func tableView(tableView: UITableView,viewForHeaderInSection section: int) -> UIView? {
    let header = tableView.dequeueReusableHeaderFooterViewWithIdentifier("header") as? CollapsibleTableViewHeader ?? CollapsibleTableViewHeader(reusEIDentifier: "header")

    header.titleLabel.text = sections[section].name
    header.arrowLabel.text = ">"
    header.setCollapsed(sections[section].collapsed)

    header.section = section
    header.delegate = self

    return header
}

普通的cell就很简单了,没什么好说的:

override func tableView(tableView: UITableView,cellForRowATindexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell? ?? UITableViewCell(style: .Default,reusEIDentifier: "cell")

    cell.textLabel?.text = sections[indexPath.section].items[indexPath.row]

    return cell
}

最后一步. 如何收起和展开?

思路超级简单!如果该section的collapsed值为true,我们就将这个section里所有cell的高度都设为0,否则为 44.0!

override func tableView(tableView: UITableView,heightForRowATindexPath indexPath: NSIndexPath) -> CGFloat {
    return sections[indexPath.section].collapsed! ? 0 : 44.0
}

切换收起和展开的函数如下:

extension CollapsibleTableViewController: CollapsibleTableViewHeaderDelegate {
    func toggleSection(header: CollapsibleTableViewHeader,section: int) {
        let collapsed = !sections[section].collapsed

        // Toggle collapse
        sections[section].collapsed = collapsed
        header.setCollapsed(collapsed)

        // Adjust the height of the rows inside the section
        tableView.beginupdates()
        for i in 0 ..< sections[section].items.count {
            tableView.reloadRowsATindexPaths([NSIndexPath(forRow: i,inSection: section)],withRowAnimation: .AutomatiC)
        }
        tableView.endupdates()
    }
}

注意到我们不是简单的重绘整个section,实际上我们只需要重绘section里的所有cell就好,这样做的好处是避免了section header因重绘时闪烁的效果,最重要是的可以让我们更平滑地处理我们想要的动画效果,例如旋转那个箭头,改变背景颜色等等。

好了就这么多吧,如果你很感兴趣,请参源码。

更多的关于table section收起和展开的项目

有时候你可能想要在grouped-style的table里实现section的收起和展开,我写了另外一个demo,https://github.com/jeantimex/ios-swift-collapsible-table-section-in-grouped-section. 实现的方法其实很类似。


作者: Yong Su @ Box Inc.

大佬总结

以上是大佬教程为你收集整理的如何实现可收起和展开的Table Section全部内容,希望文章能够帮你解决如何实现可收起和展开的Table Section所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。