【发布时间】:2015-11-29 16:23:36
【问题描述】:
我正在构建一个 iOS 计算器应用程序,它有一个 History 标签,显示所有以前的计算,这些计算都显示在一行上(例如 30 * 10 = 300 4 * 300 = 1200 )。我将标签放在 UIScrollView 中,这样当标签比屏幕宽时,我可以水平滚动浏览历史记录。我将标签定位为在滚动视图内水平和垂直放置,并将标签限制在故事板中的滚动视图中。
在我将计算添加到历史记录后,在我的视图控制器中,我检查了一个属性 canVerticallyScroll,它表明我通过扩展添加到 UIScrollView。如果 ScrollView 内容的宽度比屏幕宽,则返回 true。如果是这样,我希望它使用 setContentsOffset 滚动到最后。
这是我的视图控制器中的代码:
func saveResultTohistory(var operands: Array<Double>) {
if operands.count == 2 { // Unary operation
historyLabel.text = historyLabel.text! + operation + "\(operands.removeFirst()) = \(displayValue) "
} else if operands.count == 3 { // Binary operation
historyLabel.text = historyLabel.text! + "\(operands.removeFirst()) " + operation + " \(operands.removeFirst()) = \(displayValue) "
}
updateScrollView() // Update the position in the historyScroller
}
func updateScrollView() {
if historyScroller.canVerticallyScroll {
let end = CGPointMake(historyScroller.frame.size.width, 0)
historyScroller.setContentOffset(end, animated: true)
}
}
这里是扩展名:
extension UIScrollView {
var canVerticallyScroll: Bool {
get {
let widthOfScrollView = self.frame.size.width
let widthOfContent = self.contentSize.width
return widthOfContent > widthOfScrollView
}
}
}
这个行得通,但是不准确,因为第一次计算加到label的时候,ScrollView的contentSize是(0.0),不能这样,因为label里面有文字,应该让说 (50, 0)。在我向标签添加另一个计算后,contentSize 更新为 (50, 0),同时知道标签比这更宽,因为它现在包含两个计算。
所以基本上一切正常,除了当我尝试读取 contentSize 时,我没有得到准确的值。为什么我没有得到 UIScrollView 的实际 contentSize?
【问题讨论】:
标签: ios iphone swift uiscrollview