2015-05-26 77 views
2

我在更新我的UIScrollView的大小以适应我的UITableView高度变化时遇到了一些问题。我的UITableView不滚动。相反,我的视图的大小根据我的UITableView中的单元数量而变化。更新基于UIScrollView的UITableView高度的内容大小

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

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

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

下面是一个例子:

enter image description here

当我从一个数据集有更多的细胞去。少一个。你可以看到我能够向下滚动得远远超出我应有的能力。 (contentSize的末尾应该是在白色区域后停止16点

在尝试解决这个问题一段时间后,我确实设法让某些东西有效,我从API获取数据,有时需要一个。很长一段时间来获取。然而,当它这样做在我的tableView更新所有的数据我能够给contentsize解决什么,我想用下面的代码行:

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

首先行动的工作之后,是(之前我试图更新数据)但不幸的是,似乎并没有做任何事情。

那么如何我可以尽快重新加载我的UITableView与来自CoreData的数据(在尝试获取新数据之前)正确设置我的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() 
    } 

} 

我也试图把滚动视图相关线路的约束更新之前,但也不能工作。

然而,下面是使用的代码相同的一行我updatePortfolio()函数,并运行良好。一旦运行完成后,我的内容查看被设置为正确的尺寸。

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文件。

任何帮助将不胜感激!

+0

我很困惑为什么你会使用tableView和scrollView,因为tableViews是scrollViews的子类,因此已经可以滚动。 – Tim

+0

我的视图中有其他数据,而不仅仅是tableView中的数据。如果你看截图,你可以看到单元格周围有一个圆形的边框。在我的tableView上方,我有其他基本数据,线图,饼图,统计等。我需要能够滚动到这些。或使用scrollView滚动到底部。仅使用一个,不是一种选择。 –

回答

0

我认为你正在寻找的是分组tableview风格。

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

使用这种风格会为您节省大量工作。如果我明白你的问题。

+0

感谢您的回复。 我认为有一点沟通不畅,我的tableView下面没有“无限”单元。它保留了viewController在新数据之前的内容。 如果例如最后一次更新有9个单元。而我现在加载的那个有23个。我的屏幕停在9点(我可以看到更多的使用反弹,但直到我的更新功能完成,我看不到其余)。同样,如果我有30个单元格,我更新并且只有9个单元格。我可以比9个单元格滚动得多。 这绝对不是无限细胞的问题。这是内容(可滚动区域) –

0

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

在scrollView中,确保tableView的顶部和底部固定在滚动视图上。然后,如果您希望scrollView缩小tableView,请确保scrollView不会固定在其父视图的底部。

+0

我没有任何关于UIScrollView底部的约束。我对scrollView本身的唯一约束是:'H:| [contentView(contentWidth)]'其他每个约束都与contentView及其子视图有关。现在我的contentView被设置为以下约束:“V:| -16- [pYieldsView] -16- [pDivView] -16- [pHoldingsView] -16- |”'因为我需要底部的16p填充。但它应该随着pHoldingsView(它根据UITableView改变高度)一起增长并且它总是第一次获得正确的高度。我做错了吗? –

+0

让我使用约束/滚动视图设置编辑我的问题。 :) –

+0

我添加了我的UIScrollView的设置到我的问题的底部。 :)希望这可以帮助,如果它在那里我错了。 –

相关问题