【问题标题】:UITableViewCell has inconsistent UIView animation during revealUITableViewCell 显示期间 UIView 动画不一致
【发布时间】:2015-11-17 17:39:47
【问题描述】:

我正在开发一个基于 Swift 2.0(和自动布局)的项目。我正在尝试使用简单的扩展器控件构建视图控制器。用户单击标题位,它会展开以显示选择表。

它可以工作,但最初的显示有点奇怪。用户第一次单击标题时,它按预期展开,但表格内容从左侧略微滑入。在随后的点击中,它会在没有额外动画的情况下展开。

如果可以的话,我想消除这种轻微的“滑入”。但是我对此很陌生,以至于我不完全理解我做错了什么。事实证明,搜索 Google 和 SO 令人沮丧。我不认为我知道正确的术语来解释正在发生的事情。

我已包含示例代码来说明我在做什么。我还包括了一个动画,这样你就可以看到正在发生的事情。谢谢!

代码:

import UIKit

class ViewController: UIViewController, UITableViewDataSource {
    @IBOutlet weak var tableViewHeight: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        tableViewHeight.constant = 0
    }

    @IBAction func openTable(sender: AnyObject) {
        if tableViewHeight.constant == 0 {
            tableViewHeight.constant = 220
        } else {
            tableViewHeight.constant = 0
        }

        UIView.animateWithDuration(0.3, animations: {
            self.view.layoutIfNeeded()
        })
    }

    // MARK: tableView stuff
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = "Cell \(indexPath.item)"
        return cell
    }

}

图片:

【问题讨论】:

    标签: ios swift uitableview uiview


    【解决方案1】:

    您应该尝试在显示之前进行单元格布局并避免这种奇怪的效果。

        func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
          let cell = // get your cell for indexPath here
          cell.layoutIfNeeded()
        }
    

    【讨论】:

    • 所以这主要回答了我的问题。我所做的是在 layoutIfNeeded 调用之前使用 UIView.setAnimationsEnabled(false) 禁用 UIView 动画,然后在之后将它们重新打开。
    • @hernan43 很高兴为您提供帮助。
    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 2017-11-24
    • 2010-10-23
    • 1970-01-01
    相关资源
    最近更新 更多