수학적 접근

[Xcode/Swift] AutoLayout에서 UIScrollView 다루기 본문

개발/iOS

[Xcode/Swift] AutoLayout에서 UIScrollView 다루기

평등수렴 2020. 2. 5. 17:48
반응형

이 글에서는 ScrollView를 다루는 간단한 방법을 알아볼 것입니다.

 

 

 

ScrollView는 다른 View에 비해 Constraint를 잡는 방법이 까다로워서 처음 접하게 될 경우 어려울 수 있다고 생각합니다.

 

ScrollView는 ScrollView 안에 있는 컨텐츠의 크기를 의미하는 Viewport라는 개념이 있기 때문인데,

 

단순히 View 자체의 위치만 잡으면 되는 다른 View들과는 달리 이 Viewport를 고려해주어야 합니다.

 

 

먼저 UIScrollView 하나를 Safe Area 에 가득 차도록 배치해보겠습니다.

UIScrollView를 생성하고 나면 왼쪽 트리에 UIScrollView 하위에 아래와 같은 두 가지 뷰가 같이 생성되어 있는 것을 확인할 수 있습니다.

 

이 두 개는 쓸모가 없어서 지울 것입니다. Xcode가 11 버전으로 업데이트되면서 추가된 것들인데, 아직 사용 방법을 잘 모르겠습니다. 하지만 이것이 없어도 잘 동작하게 만들 수 있습니다.

 

이것은 그냥 지울 수는 없고, 오른쪽 속성 창에서 아래의 체크박스를 해제하여 없앨 수 있습니다.

그리고 Safe Area의 위, 왼쪽, 오른쪽, 아래에 Constraint를 설정합니다.

 

이제 UIScrollView 안에 우리가 넣고 싶은 View를 넣어봅시다.

여기서는 UILabel 하나를 넣어서, UILabel 안의 내용의 길이가 길어서 화면의 크기 범위를 넘어갈 때

스크롤이 생기게 하여, UILabel 안의 내용을 스크롤을 통해 모두 볼 수 있도록 만들어보겠습니다.

 

먼저 UILabel 하나를 삽입합니다.

 

UILabel을 UIScrollView 안에 넣고 나서 UIScrollView 를 선택해보면 아래와 같이 Constraint 오류가 발생한 것을 확인할 수 있습니다.

UIScrollView의 Constraint는 앞에서 잘 잡아놨는데 왜 이런 오류가 났을까요?

 

어떤 오류가 났는지 왼쪽 창에서 확인해보겠습니다.

 

Scrollable Content Size Ambiguity 라는 에러가 났습니다.

 

이 에러의 자세한 정보를 보면,

 

"UIScrollView is computed automatically based upon the constraints of its subviews"

 

라고 되어있습니다.

 

해석해보면 스크롤뷰의 크기는 subview(안에 있는 뷰)의 크기에 의해 결정된다는 뜻입니다.

 

즉, subview들은 UIScrollView 안에서 constraint가 확실하게 정해져야 한다는 것입니다.

 

현재 예제로 보여드리고 있는 것은 UILabel 하나만을 subview로 두고 있기 때문에

 

UIScrollView 안의 UILabel의 constraint를 아래와 같이 잡으면 끝납니다.

 

 

위와 같이 Constraint 잡는 방법

 

1. 먼저 아래와 같이 'Add Missing Constraints' 를 눌러 기본적인 Constraint를 잡아줍니다.

그러면 아래와 같이 constraint가 잡힙니다(숫자는 Label이 놓여있던 위치에 따라 다름).

 

 

2. Label을 화면의 좌측 상단에 붙인 다음, constraint의 상수값을 아래와 같이 바꿉니다.

Label.top = top

trailing = Label.trailing

bottom = Label.bottom

Label.leading = leading

 

- trailing = Label.trailing인 이유

 나중에 label을 화면 폭에 맞게 확장하기 위해서입니다.

 

- bottom = Label.bottom인 이유

 UILabel은 UIScrollView의 아래쪽과 멀리 떨어져있는데 왜 offset(constant) 값을 0으로 설정했는지 궁금할 것입니다.

 그것은 앞에서 말했던 Viewport 개념 때문입니다.

 여기서 UILabel은 Viewport 역할을 하고 있습니다. ScrollView 안에서 보여지는 내용의 전부이기 때문입니다.

 그래서 ScrollView의 끝쪽을 Viewport의 끝쪽과 맞춰주어야 합니다.

 

 

3. 그리고 UILabel의 폭을 ScrollView와 맞춰주기 위해, UILabel 위에 마우스 커서를 놓은 상태에서 우클릭 - 드래그하여

UIScrollView로 끌어놓습니다.

그러면 위와 같은 선택창이 나오고, 여기서 Equal Widths를 선택합니다.

 

 

그러면 위와 같은 constraints가 생기는데,

Label의 width는 부모(UIScrollView)의 width와 일치시킬 것이기 때문에 저 숫자(multiplier)를 1로 바꿔줍니다.

 

이 과정을 모두 마치면 완성입니다.

 

이제 스크롤뷰가 잘 동작하는지 확인하기 위해, 긴 텍스트를 넣어보겠습니다.

더보기

What is Lorem Ipsum?

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Why do we use it?

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

 

Where does it come from?

Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.

The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.

Where can I get some?

There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.

위와 같은 Lorem Ipsum 텍스트를 우리의 UILabel에 넣어보겠습니다.

 

그러면 우선은 이렇게 나오는데, 이것은 UILabel 의 속성 때문이므로 오른쪽 속성창에서 Lines를 0으로 바꿔줍니다.

 

그러면 아래와 같이 잘 표시되는 것을 확인할 수 있습니다.

 

 

아래로 늘어난 파란색 줄들은 Viewport의 크기를 표시하는 것들입니다.

 

여기까지 하고 기기에서 확인해보면 잘 작동하는 것을 확인할 수 있습니다.

 

 

만약 UIScrollView 안에 여러 개의 subview를 넣고 싶거나, 스크롤 뷰 내에 여백을 주는 등의 작업을 하고 싶으면,

 

이 글의 UILabel 대신 subview를 담을 수 있는 컨테이너를 넣은 다음, 그 안에서 작업하면 됩니다.

 

이상의 내용을 담은 프로젝트를 github에 올려두었습니다.

 

 

 

dmseo1/dm-tistory-ios-scrollview

Contribute to dmseo1/dm-tistory-ios-scrollview development by creating an account on GitHub.

github.com

 

 

 

+++++

 

내가 마시고 있는 생수는 안전한 생수일까?

15년도부터 생수 수질기준 부적합 판정을 받은 이력을 확인할 수 있는 앱, <바른생수>를 출시하였습니다.

 

관심 한번씩만 부탁드립니다 ^^

 

바로가기!

 

 

반응형

'개발 > iOS' 카테고리의 다른 글

[Xcode/Swift] 화면 아래에 표시되는 PickerView 만들기  (0) 2020.02.04
Comments