我在更新我的UIScrollView
的大小以適應我的UITableView
高度變化時遇到了一些問題。我的UITableView
不滾動。相反,我的視圖的大小根據我的UITableView
中的單元數量而變化。更新基於UIScrollView的UITableView高度的內容大小
我有一個UIViewController
我用來加載3個不同的數據集。 (這需要更新我的UITableView以適應不同數量的數據)
因此,當我加載第一個數據集時,它工作正常。
但是,如果我加載一個新的之後,與不同數量的單元格。我的UIScrollView的contentSize現在是錯誤的。 (它保持以前數據集的大小)。
下面是一個例子:
當我從一個數據集有更多的細胞去。少一個。你可以看到我能夠向下滾動得遠遠超出我應有的能力。 (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文件。
任何幫助將不勝感激!
我很困惑爲什麼你會使用tableView和scrollView,因爲tableViews是scrollViews的子類,因此已經可以滾動。 – Tim
我的視圖中有其他數據,而不僅僅是tableView中的數據。如果你看截圖,你可以看到單元格周圍有一個圓形的邊框。在我的tableView上方,我有其他基本數據,線圖,餅圖,統計等。我需要能夠滾動到這些。或使用scrollView滾動到底部。僅使用一個,不是一種選擇。 –