SwiftUI를 사용하여 UI를 구성할 때, 컨텐츠의 길이에 따라 스크롤이 필요하거나 필요하지 않은 상황을 처리해야 할 때가 있습니다. iOS 16.4 이상에서는 간단한 방법으로 이를 구현할 수 있지만, 하위 버전에서는 기존 SwiftUI 기능을 활용해 직접 구현해야 합니다.
iOS 16.4 이상: .scrollBounceBehavior(.basedOnSize) 사용하기
iOS 16.4부터 Apple은 .scrollBounceBehavior라는 새로운 modifier를 도입했습니다. 이 modifier는 스크롤 뷰의 바운스 동작을 컨텐츠 크기에 따라 동적으로 조정할 수 있도록 도와줍니다. 이를 활용하면 컨텐츠의 길이가 스크롤 뷰의 크기보다 짧은 경우 바운스 효과를 비활성화하고, 그렇지 않은 경우 활성화하는 간단한 처리가 가능합니다.
코드 예제
import SwiftUI
struct ContentView: View {
var body: some View {
ScrollView {
VStack(spacing: 20) {
ForEach(0..<10) { index in
Text("Item \(index)")
.padding()
.background(Color.blue.opacity(0.2))
.cornerRadius(10)
}
}
.padding()
}
.scrollBounceBehavior(.basedOnSize)
}
}
위 코드에서 .scrollBounceBehavior(.basedOnSize)를 추가함으로써, 컨텐츠 길이에 따라 적절한 스크롤 동작이 자동으로 적용됩니다.
iOS 16.4 미만: ViewThatFits 활용하기
iOS 16.4 이전 버전에서는 .scrollBounceBehavior를 사용할 수 없으므로, ViewThatFits를 사용하여 스크롤 가능 여부를 수동으로 처리해야 합니다. ViewThatFits는 자식 뷰들 중에서 가장 적합한 뷰를 선택하여 렌더링하는 컨테이너로, 이를 활용해 두 가지 뷰(스크롤이 필요한 뷰와 그렇지 않은 뷰)를 조건에 따라 전환할 수 있습니다.
코드 예제
import SwiftUI
struct ContentView: View {
var body: some View {
ViewThatFits(in: .vertical) {
ScrollView {
content
}
content
}
}
var content: some View {
VStack(spacing: 20) {
ForEach(0..<10) { index in
Text("Item \(index)")
.padding()
.background(Color.green.opacity(0.2))
.cornerRadius(10)
}
}
.padding()
}
}
ViewThatFits를 사용하면 컨텐츠 길이에 따라 스크롤 뷰와 일반 뷰가 동적으로 전환되도록 설정할 수 있습니다. 스크롤이 필요하지 않은 경우 스크롤 뷰가 아닌 일반 뷰가 렌더링됩니다.
결론
SwiftUI에서 컨텐츠 길이에 따른 스크롤 동작을 설정하려면 사용하는 iOS 버전에 따라 접근 방법을 달리해야 합니다.
- iOS 16.4 이상에서는 .scrollBounceBehavior(.basedOnSize)를 간단히 추가하여 구현할 수 있습니다.
- iOS 16.4 미만에서는 ViewThatFits를 활용해 스크롤이 필요한 경우와 그렇지 않은 경우를 처리할 수 있습니다.
Refrences
- https://developer.apple.com/documentation/swiftui/viewthatfits
ViewThatFits | Apple Developer Documentation
A view that adapts to the available space by providing the first child view that fits.
developer.apple.com
- https://developer.apple.com/documentation/swiftui/view/scrollbouncebehavior(_:axes:)
scrollBounceBehavior(_:axes:) | Apple Developer Documentation
Configures the bounce behavior of scrollable views along the specified axis.
developer.apple.com