0
votes

I'm building a building a iOS calculator app which has a History label that shows all the previous calculations, which are all displayed on one line (e.g. 30 * 10 = 300 4 * 300 = 1200 ). I put the label inside a UIScrollView so that when the label gets wider than the screen I can horizontally scroll through the history. I positioned the label to fit horizontally and vertically inside the scrollview and constrained the label to the scrollview in my storyboard.

In my view controller after I add a calculation to the history, I check a property canVerticallyScroll that indicates I added to UIScrollView through an extension. This returns true if the width of the ScrollView content is wider than the screen. If so I want it to scroll to the end by using setContentsOffset.

Here's the code in my view controller:

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)
        }
    }

And here the extension:

extension UIScrollView {
    var canVerticallyScroll: Bool {
        get {
            let widthOfScrollView = self.frame.size.width
            let widthOfContent = self.contentSize.width
            return widthOfContent > widthOfScrollView
        }
    }
}

This works, but it's not accurate, because when the first calculation is added to the label, the contentSize of the ScrollView is (0.0), which it can't be because the label has text in it and it should be let say (50, 0). after I add another calculation to the label the contentSize updates to (50, 0), while know the label is wider than this because it now contains two calculations.

So basically everything works except that when I try to read the contentSize I do not get an accurate value. Why am I not getting the actual contentSize of UIScrollView?

1

1 Answers

0
votes

The scrollView's contentSize is updated by the run loop after your code has run.

You're changing the historyText label's text, but not immediately updating its size. Because its size hasn't changed yet, its container's size won't have changed when you access it.