Text가 Truncated되는 것 방지하기 @Work

SteadySlower·2023년 3월 18일
0

SwiftUI

목록 보기
40/64

절대로 Truncated 되면 안되는 Text를 truncated를 방지하는 방법입니다.

예시 코드

이번에 새로운 프로젝트의 이메일 입력 화면을 만들면서 겪은 일입니다. 이메일 입력 화면을 만들면서 title과 text field 사이에 email의 포맷에 대한 안내문을 넣었는데 그 문구가 너무 길어서 truncated 되는 현상이 발생했습니다.

아래는 위 화면을 단순화해서 만들어 보았는데요. 이 입력 화면은 각각의 View Component의 패딩이 많이 들어가서 중간에 존재하는 Text를 전부 표현할 공간이 부족해서 아래 캡쳐와 같이 공간이 truncated된 상황입니다.

하지만 이 Text가 절대로 truncated 되면 안된다고 가정해봅시다.

import SwiftUI

struct InterimView: View {
    
    @State var email: String = ""
    
    var body: some View {
        VStack {
            Text("Email Input")
                .font(.system(.largeTitle))
                .padding(.vertical, 100)
            Text("This \"Long\" Text is about Email format which shouldn't be trucated This \"Long\" Text is about Email format which shouldn't be trucated This \"Long\" Text is about Email format which shouldn't be trucated This \"Long\" Text is about Email format which shouldn't be trucated This \"Long\" Text is about Email format which shouldn't be trucated")
                .padding(.vertical, 50)
            TextField("Input Email", text: $email)
                .border(.gray)
                .padding(.horizontal, 50)
                .padding(.vertical, 50)
            Button("Send") { }
                .padding(.vertical, 100)
        }

    }
}

lineLimit

처음으로 떠올린 방법은 lineLimit를 사용하는 방법이었는데요. lineLimit는 text가 max로 차지할 수 있는 최대 줄수를 정할 수 있습니다. 아래 설명에 따르면 nil을 전달하면 limit를 제거할 수 있습니다.

하지만 이 방법은 정해진 View의 크기 안에서 표현할 수 있는 line의 수를 정해주는 것입니다. 지금처럼 위 아래 View의 공간이 없을 때는 적절한 방법이 아닙니다.

Text("This \"Long\" Text is about Email format which shouldn't be trucated This \"Long\" Text is about Email format which shouldn't be trucated This \"Long\" Text is about Email format which shouldn't be trucated This \"Long\" Text is about Email format which shouldn't be trucated This \"Long\" Text is about Email format which shouldn't be trucated")
    .padding(.vertical, 50)
    .lineLimit(nil)

.fixedSize()

이 케이스에 가장 적절한 방법은 fixedSize를 활용하는 방법입니다. fixedSize의 설명에도 위와 동일한 예시가 주어져있습니다.

fixedSize에서 vertical을 false로 설정하면 Text는 부모 View의 크기를 넘어서서 표현될 수 있습니다. 아래 캡쳐처럼 Text에 할당된 공간이 부족해도 모든 text를 표현할 수 있습니다. 물론 편리한 기능입니다만 그 만큼 공간을 더 차지하게 되므로 다른 View들이 위아래로 밀립니다. Text의 크기가 너무 커지면 다른 View들은 화면 밖으로 나가버릴 수도 있습니다.

Text("This \"Long\" Text is about Email format which shouldn't be trucated This \"Long\" Text is about Email format which shouldn't be trucated This \"Long\" Text is about Email format which shouldn't be trucated This \"Long\" Text is about Email format which shouldn't be trucated This \"Long\" Text is about Email format which shouldn't be trucated")
    .padding(.vertical, 50)
    .fixedSize(horizontal: false, vertical: true)

profile
백과사전 보다 항해일지(혹은 표류일지)를 지향합니다.

0개의 댓글