![](/img/trans.png)
[英]Why is UIScrollView contentSize ignored in IB but works when I set it in my viewDidAppear method?
[英]Why am I not getting the actual contentSize of UIScrollView?
我正在構建一個iOS計算器應用程序,該應用程序的“歷史記錄”標簽顯示了所有以前的計算,並且全部顯示在一行上(例如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
}
}
}
此方法有效,但不准確,因為將第一個計算添加到標簽時,ScrollView的contentSize為(0.0),這不是因為標簽中包含文本,所以應該說(50 ,0)。 在向標簽添加另一個計算之后,contentSize更新為(50,0),同時知道標簽比這更寬,因為它現在包含兩個計算。
因此,基本上所有的東西都可以正常工作,只是當我嘗試讀取contentSize時,我沒有獲得准確的值。 為什么我沒有得到UIScrollView的實際contentSize?
在代碼運行之后,滾動循環將scrollView的contentSize
更新。
您正在更改historyText
標簽的文本,但沒有立即更新其大小。 由於其大小尚未更改,因此訪問時其容器的大小不會更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.