TableView使用Swift 3展开/折叠

时间:2017-04-04 08:32:29

标签: uitableview swift3 tableviewcell uitableviewsectionheader

我确实在swift 3中折叠/展开了表格单元格。但是,我想在标题标题中添加一些填充底部。在我的屏幕截图中,标题1和标题2之间没有填充。

另一个问题是如何将箭头图像向右移动?

enter image description here

这是我的代码。

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let headerView = UIView.init(frame: CGRect(x: 0, y: 0, width: 300, height: 28))
    var imageView = UIImageView()
    if (expandSections.contains(section)) {
        imageView = UIImageView.init(frame: CGRect(x: 7, y: 5, width: 25, height: 25))
        imageView.image = UIImage(named: "down_image")

    } else {
        imageView = UIImageView.init(frame: CGRect(x: 7, y: 5, width: 25, height: 25))
        imageView.image = UIImage(named: "up_image")
    }

    let headerTitle = UILabel.init(frame: CGRect(x: 38, y: 4, width: 250, height: 28))
    headerTitle.text = sectionData[section]
    headerTitle.textColor = UIColor.white

    let tappedSection = UIButton.init(frame: CGRect(x: 0, y: 0, width: headerView.frame.size.width, height: headerView.frame.size.height))
    tappedSection.addTarget(self, action: #selector(sectionTapped), for: .touchUpInside)
    tappedSection.tag = section

    headerView.addSubview(imageView)
    headerView.addSubview(headerTitle)
    headerView.addSubview(tappedSection)
    headerView.backgroundColor = UIColor.lightGray
    return headerView
}

1 个答案:

答案 0 :(得分:0)

试试这个,在这里我在headerView中添加了另一个视图。然后只有你可以在headerView中添加填充。

  func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {

        let headerView = UIView.init(frame: CGRect(x: 0, y: 0, width: 300, height: 28))

        let internalView = UIView.init(frame: CGRect(x: 0, y: 0, width: 300, height: 25))

        var imageView = UIImageView()

        if (expandSections.contains(section)) {

            imageView = UIImageView.init(frame: CGRect(x: internalView.frame.size.width - 10 , y: 5, width: 25, height: 25))
            imageView.image = UIImage(named: "down_image")

        } else {
            imageView = UIImageView.init(frame: CGRect(x: internalView.frame.size.width - 10 , y: 5, width: 25, height: 25))
            imageView.image = UIImage(named: "up_image")
        }

        let headerTitle = UILabel.init(frame: CGRect(x: 38, y: 4, width: 250, height: 28))
        headerTitle.text = sectionData[section]
        headerTitle.textColor = UIColor.white

        let tappedSection = UIButton.init(frame: CGRect(x: 0, y: 0, width: headerView.frame.size.width, height: headerView.frame.size.height))
        tappedSection.addTarget(self, action: #selector(sectionTapped), for: .touchUpInside)
        tappedSection.tag = section

        internalView.addSubview(imageView)
        internalView.addSubview(headerTitle)
        internalView.addSubview(tappedSection)

        headerView.addSubview(internalView)
        headerView.backgroundColor = UIColor.lightGray
        return headerView
    }