在IOS中创建动态节头

时间:2016-09-25 16:23:48

标签: ios swift uitableview

我正在尝试使用动态高度创建自定义节标题。我创建了一个非常简化的应用程序版本,我在其中显示一个方形图像作为表格部分标题。图像高度与屏幕宽度相同。 tableView必须是动态的,因为图像高度随屏幕宽度而变化。即使应用程序有效,我也无法摆脱约束警告。这是一个非常简单的应用程序,我不知道为什么它会给我带来约束错误。似乎图像约束的1:1比率是问题的根源。我已经附加了我的xib文件,代码和输出截图的约束。

Xib Constraint

Simulator Output

class ViewController: UIViewController {

    @IBOutlet weak var myTableView: UITableView!

    var xibRef: CustomHeaderView!
    var numberOfSection = 3

    override func viewDidLoad() {
        super.viewDidLoad()
        myTableView.delegate = self
        myTableView.dataSource = self

        // Register Xib
        let nib = UINib(nibName: "CustomHeaderView", bundle: nil)
        self.xibRef = nib.instantiateWithOwner(self, options: nil)[0] as? CustomHeaderView
        self.myTableView.registerNib(nib, forHeaderFooterViewReuseIdentifier: "CustomHeaderView")
    }
}

extension ViewController: UITableViewDataSource, UITableViewDelegate {

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath)

        cell.textLabel!.text = "section \(indexPath.section) row \(indexPath.row)"

        return cell
    }


    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return numberOfSection
    }

    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return UITableViewAutomaticDimension
    }

    func tableView(tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
        return view.frame.size.width
    }

    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let cell = tableView.dequeueReusableHeaderFooterViewWithIdentifier("CustomHeaderView") as! CustomHeaderView

        return cell
    }
}

0 个答案:

没有答案