我在更新我的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滚动到底部。仅使用一个,不是一种选择。 –