Monday, October 29, 2018

Introduction to UIScrollView

The contents in your app might be cut off when they exceed the device's screen. Developers have to make them scrollable so the user can see all of the contents. For example, if you have a label (UILabel object) to display a hundred lines of article, you have to put it in a scroll view (UIScrollView object) so that the user can scroll up and down or left and right to see the whole article.

According to Apple's documentation, A scroll view (UIScrollView object) is a view whose origin is adjustable over the content view. It clips the contents to its frame and track the movement of fingers and adjust the origin accordingly. The origin refers to the original position on the screen.




Sample App


I'm developing a pet project called MyCalculator. The image below shows how I designed it in the Interface Builder (IB). I put the label named "Display Sub Section" to display the current operation the user's entering in a scroll view named "Display Sub Section Scroll View". The label for the current operation had a blue background but it did not show up in the image below because its size was zero by default at the design time without any constraints. Note that the scroll view had green background.


Then, I resized the label manually in IB.


But at runtime, the label didn't get wider even though its text was longer that its width, and so it couldn't be scrolled because the label's width is shorter than the scroll view's.


After that, I set constraints for the label's bottom, top, leading, and trailing equal to the scroll view's bottom, top, leading and trailing, respectively.


And it worked. I could scroll the label (blue background) left and right and the scroll indicator appeared but I had to enter the operation until it exceeded the screen's width first.


Note that the scroll view's contentSize.width property is greater than the scroll view's bounds.width property when the label's text exceeds the screen's width. Then, while you're scrolling, the scroll view adjust its origin to show part of the content accordingly.

Problem 1


I want to align the current operation the user's entering to the right as shown in the image below.


But, the content, the label, is left aligned by default when it's inside a scroll view. I cannot change it. It's the top-left corner of the scroll view's origin. When the current operation the user's entering exceeds the screen's width, the user will be able to scroll. I changed the Alignment setting of both the label and the scroll view but no effect. However, I found a workaround by rotating the scroll view as below.

displaySubSectionScrollView.transform = displaySubSectionScrollView.transform.rotated(by: CGFloat(Float.pi))
displaySubSection.transform = displaySubSection.transform.rotated(by: CGFloat(Float.pi))

This post explains in details about the rotated() method.






No comments:

Post a Comment