2015-05-26 75 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的設置到我的問題的底部。 :)希望這可以幫助,如果它在那裏我錯了。 –

相關問題