ios - 更新基于 UITableView 高度的 UIScrollView 的 contentSize

标签 ios uitableview swift uiscrollview

我在更新 UIScrollView 的大小以适应我的 UITableView 高度变化时遇到了一些问题。

我的 UITableView 不可滚动。相反,我的 View 大小会根据 UITableView 中的单元格数量而变化。

我有一个 UIViewController 用于加载 3 个不同的数据集。 (这需要经常更新我的 UITableView 以适应不同数量的数据)

所以当我加载第一个数据集时它工作正常。

但是,如果我在那之后加载一个新的,具有不同数量的细胞。我的 UIScrollView 的 contentSize 现在是错误的。 (无论以前的数据集是什么,它都会保持大小)。

这是一个例子:

enter image description here

我从具有更多单元格的数据集出发的地方。少花钱。你可以看到我能够向下滚动比我应该能够的更多。 (contentSize 的结尾应该在白色区域后 16 个点处停止。

在尝试解决这个问题一段时间后,我确实设法让一些东西工作了。我从 API 获取数据,有时需要很长时间才能获取。但是,当它更新完我的 tableView 中的所有数据后,我可以使用以下代码行将内容大小固定为我想要的大小:

self.scrollView.contentSize = CGSize(width:self.view.bounds.width, height: self.contentView.frame.height)

在那之后的第一个行动就是把它放得更早。 (在我尝试更新数据之前。)但不幸的是,这似乎根本没有做任何事情。

那么,如何在使用 CoreData 中的数据重新加载 UITableView 后(在尝试获取新数据之前)正确设置我的 contentSize?

这是加载数据的函数。 (这是立即发生的。这是重新加载后此函数的结束,我需要修复内容大小。

func loadPortfolio() {

    println("----- Loading Portfolio Data -----")
    // Set the managedContext again.
    managedContext = appDelegate.managedObjectContext!

    // Check what API to get the data from
    if Formula == 1 {
        formulaEntity = "PortfolioBasic"
        println("Setting Entity: \(formulaEntity)")
        formulaAPI = NSURL(string: "http://api.com/json/monthly_entry.json")
    } else if Formula == 2 {
        formulaEntity = "PortfolioPremium"
        formulaAPI = NSURL(string: "http://api.com/json/monthly_proff.json")
        println("Setting Entity: \(formulaEntity)")
    } else if Formula == 3 {
        formulaEntity = "PortfolioBusiness"
        println("Setting Entity: \(formulaEntity)")
        formulaAPI = NSURL(string: "http://api.com/json/monthly_fund.json")
    } else {
        println("Errror - Formula out of range.")
    }

    // Delete all the current objects in the dataset
    let fetchRequest = NSFetchRequest(entityName: formulaEntity)
    let a = managedContext.executeFetchRequest(fetchRequest, error: nil) as! [NSManagedObject]
    stocks.removeAll(keepCapacity: false)
    for mo in a {
        stocks.append(mo)
    }

    // Saving the now empty context.
    managedContext.save(nil)


    // Setting the first cell to be white
    cellAlteration = 0

    // Reload the tableview with the new data.
    self.pHoldingsTable.reloadData()

    tableHeight.constant = CGFloat(stocks.count*50)


    // This doesn't work here for some reason?
    self.scrollView.contentSize = CGSize(width:self.view.bounds.width, height: self.contentView.frame.height)

println("Finished loading portfolio")


    self.view.hideLoading()

    dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) {
        self.updatePortfolio()
    }

}

我也试过将 scrollView 相关的行放在约束更新之前,但这也没有用。

但是。下面是我的 updatePortfolio() 函数,它使用完全相同的代码行,并且工作正常。一旦完成运行,我的 contentView 就会被设置为正确的大小。

func updatePortfolio() {
    println("Updating Portfolio")
    if Reachability.isConnectedToNetwork() == false {
        println("ERROR: - No Internet Connection")
    } else {
        // Delete all the current objects in the dataset
        let fetchRequest = NSFetchRequest(entityName: formulaEntity)
        let a = managedContext.executeFetchRequest(fetchRequest, error: nil) as! [NSManagedObject]
        for mo in a {
            managedContext.deleteObject(mo)
        }
        // Removing them from the array
        stocks.removeAll(keepCapacity: false)
        // Saving the now empty context.
        managedContext.save(nil)

        // Set up a fetch request for the API data
        let entity =  NSEntityDescription.entityForName(formulaEntity, inManagedObjectContext:managedContext)
        var request = NSURLRequest(URL: formulaAPI!)
        var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
        var formula = JSON(data: data!)

        // Loop through the api data.
        for (index: String, portfolio: JSON) in formula["portfolio"] {

            // Save the data into temporary variables
            stockName = portfolio["name"].stringValue.lowercaseString.capitalizedString
            ticker = portfolio["ticker"].stringValue
            purchasePrice = portfolio["purchase_price"].floatValue
            weight = portfolio["percentage_weight"].floatValue


            // Set up CoreData for inserting a new object.
            let stock = NSManagedObject(entity: entity!,insertIntoManagedObjectContext:managedContext)

            // Save the temporary variables into coreData
            stock.setValue(stockName, forKey: "name")
            stock.setValue(ticker, forKey: "ticker")
            stock.setValue(action, forKey: "action")
            stock.setValue(purchasePrice, forKey: "purchasePrice")
            stock.setValue(weight, forKey: "weight")

            // Doing a bunch of API calls here. Irrelevant to the question and took up a ton of code, so skipped it to make it more readable.


            // This can simply be set, because it will be 0 if not found.
            stock.setValue(lastPrice, forKey: "lastPrice")

            // Error handling
            var error: NSError?
            if !managedContext.save(&error) {
                println("Could not save \(error), \(error?.userInfo)")
            }
            // Append the object to the array. Which fills the UITableView
            stocks.append(stock)
        }

        NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
            // Setting the first cell to be white
            cellAlteration = 0
            self.tableHeight.constant = CGFloat(self.stocks.count*50)
            self.pHoldingsTable.reloadData()
            self.scrollView.contentSize = CGSize(width:self.view.bounds.width, height: self.contentView.frame.height)
            println("Finished Updating Portfolio")
        })
    }
}

我还尝试将 tableHeight 约束放在重新加载之上,就像它在更新函数中一样。但这并没有什么不同。

这是我的 UIScrollView 的设置方式:

    override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    scrollView.frame = view.bounds
    scrollView.contentSize = CGSize(width:self.view.bounds.width, height: contentView.frame.height)
}

这总是第一次得到正确的尺寸。但是因为tableView变化的时候并没有调用这个函数。它不会自动更新 contentSize。

我的 contentView.frame.height 会根据 UITableView 中的单元格数量而变化。这不是一个固定的高度。 (我从不希望我的 UITableView 本身在它的框内滚动)

此外,如果我的问题与约束相关而不是在我的函数中,我将以编程方式进行。我没有使用 Storyboard或 XIB 文件。

如有任何帮助,我们将不胜感激!

最佳答案

我认为您正在寻找的是分组 TableView 样式。

可以肯定的是:您唯一想要的就是不要在最后一个单元格下方有无限单元格,对吗?如果是这样,您应该使用分组 TableView 样式。

使用这种风格可以节省大量工作。如果我理解你的问题。

关于ios - 更新基于 UITableView 高度的 UIScrollView 的 contentSize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30457407/

相关文章:

ios - 暂停 segue 直到 IAP 交易完成

javascript - 如何使用 Javascript 或 JQuery 从 Salesforce1 应用程序导航到 iOS 13 中的其他 native 应用程序?

ios - 本地通知声音在前台不起作用

ios - 类型 'Any' 的值没有成员 'removeFromSuperview'

删除和插入具有不同高度的单元格时,UITableView 动画故障

ipad - 如何在 iPad 的 View Controller 中创建多个表格 View ?

ios - 无法使用 moveToY SKAction

ios - UIButton 重叠并意外隐藏在 UITableViewCell 中

ios - 从 AppDelegate 调用 ViewController 的成员函数

ios - 暂停菜单图层