Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/107.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 更新基于UITableView高度的UIScrollView的内容大小_Ios_Uitableview_Swift_Uiscrollview - Fatal编程技术网

Ios 更新基于UITableView高度的UIScrollView的内容大小

Ios 更新基于UITableView高度的UIScrollView的内容大小,ios,uitableview,swift,uiscrollview,Ios,Uitableview,Swift,Uiscrollview,更新我的UIScrollView的大小以适应我的UITableView高度变化时遇到一些问题 我的UITableView不可滚动。相反,我的视图的大小会根据我的UITableView中的单元格数量而变化 我有一个UIViewController,用于加载3个不同的数据集。(这需要经常更新我的UITableView以适应不同数量的数据) 因此,当我加载第一个数据集时,它工作正常 但是,如果我在那之后加载一个新的,使用不同数量的单元格。我的UIScrollView的内容大小现在是错误的。(它保持了前

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

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

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

因此,当我加载第一个数据集时,它工作正常

但是,如果我在那之后加载一个新的,使用不同数量的单元格。我的UIScrollView的内容大小现在是错误的。(它保持了前一个数据集的大小)

下面是一个例子:

我从一个有更多单元格的数据集开始。给一个更少的人。你可以看到,我可以向下滚动,比我应该能够的要远得多。(contentSize的结尾应在白色区域后16点停止

在尝试解决此问题一段时间后,我确实设法使某些内容正常工作。我从API获取数据,这有时需要很长时间才能获取。但是,当更新完tableView中的所有数据后,我可以使用以下代码行将contentsize修复为所需的大小:

self.scrollView.contentSize = CGSize(width:self.view.bounds.width, height: self.contentView.frame.height)
这之后的第一个措施奏效了,就是把它放得更早。(在我尝试更新数据之前。)但不幸的是,这似乎没有起到任何作用

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

这是加载数据的函数。(这会立即发生。在重新加载后,此函数将结束,我需要修复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本身在其框内滚动)

另外,如果我的问题与约束相关,而不是在我的函数中,我是通过编程来完成的。我没有使用故事板或XIB文件


非常感谢您的帮助!

我想您需要的是分组表视图样式

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


使用这种样式可以节省大量工作。如果我理解您的问题。

这是视图和子视图之间的固定约束问题


在scrollView中,确保将tableView的顶部和底部固定到scrollView。然后,如果希望scrollView与tableView一起缩短,请确保scrollView未固定到其父视图的底部。

我不明白为什么要使用tableView和scrollView,因为tableView是scrollView的子类,因此l已可滚动。我的视图中有其他数据,而不仅仅是tableView中的数据。如果您查看屏幕截图,您可以看到单元格周围的圆形边框。在我的tableView上方,我有其他基本数据、折线图、饼图、统计数据等。我需要能够向上滚动到这些数据。或者使用scrollView滚动到底部。仅使用一个,不是一个选项。谢谢你的回复。我认为有点沟通错误,我的tableView下没有“无限”单元格。它保持了viewController在新数据之前的内容大小。例如,上次更新有9个单元格,而我加载的现在有23个。我的屏幕在9处停止。(使用bounce,我可以看到更远的一点。但在我的更新功能完成之前,我看不到其余的)。同样,如果我有30个单元格,我会更新,只有9个。我可以比9个单元格滚动得更远。无限个单元格绝对没有问题。这是contentsize(可滚动区域)我没有关于UIScrollView的任何约束。我对scrollView本身的唯一约束是:
H:|[contentView(contentWidth)]
每一个约束都是关于contentView及其子视图的。但是,现在我的contentView设置了以下约束。
“V:|-16-[pYieldsView]-16-[pDivView]-16-[pHoldingsView]-16-|“
因为我需要底部的16p填充。但是它应该随着pHoldingsView(根据UITableView改变高度)而增长,并且第一次总是得到正确的高度。我做错了吗?让我用约束/滚动视图设置编辑我的问题。:)我将我的UIScrollView设置添加到了问题的底部。:)如果我出错了,希望这会有所帮助。