【问题标题】:Fix the aspect ratio of the first row in UITableView修复 UITableView 第一行的纵横比
【发布时间】:2015-10-31 02:42:01
【问题描述】:

我正在创建一个屏幕,想象一下 facebook 个人资料屏幕。一个 tableview 和第一个单元格是一个图像。目标是该图像保持纵横比,因此对于不同的屏幕尺寸,我不必担心它的大小。

我无法让它与任何视图一起使用,即使我设置了特定的约束,单元格也不会设置正确的高度..

我有一个显示约束的小项目,在这个链接中..

我的 VC 代码:

class ViewController: UITableViewController{

    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.dataSource = self
        self.tableView.delegate = self
        self.tableView.estimatedRowHeight = 100
        self.tableView.rowHeight = UITableViewAutomaticDimension

        self.tableView.reloadData()
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
        return cell
    }

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

我的限制:

【问题讨论】:

标签: ios iphone swift uitableview


【解决方案1】:

如果表格视图单元格的高度基本上是表格视图宽度的函数,则实现 heightForRowAtIndexPath 委托方法可能更容易返回表格视图的宽度乘以您想要的比率。这将完全消除限制,并且可能更有效。

【讨论】:

  • 这是一个很好的观点,可能还有其他高度不同的单元格,但据我所见,我可以从基于 indexPath 的高度方法返回动态。图像单元格将有一些标签,我已经设法使用自动布局。最重要的是,这让我很沮丧,因为我觉得它应该像我预期的那样工作。
【解决方案2】:

这是你应该做的:

  1. 插入表格视图标题视图
  2. viewWillLayoutSubviews 函数中更新帧高度以保持所需的纵横比。

class ViewController: UITableViewController {

    @IBOutlet weak var headerView: UIView!

    override func viewWillLayoutSubviews() {
        var frame = headerView.frame;
        // Check and see if the aspect ratio of the frame
        // of the header view is the desired aspect ratio.
        if frame.size.height != frame.width * 0.5 {
            // If it is not, update the frame
            frame.size.height = frame.width * 0.5;
            headerView.frame = frame;
            // reset the header view
            self.tableView.tableHeaderView = headerView
        }
    }
}

【讨论】:

    猜你喜欢
    • 2011-10-26
    • 2015-04-27
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2012-07-14
    • 2014-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多