Swift UI - 6. 스택
Swift UI - 6. 스택
1) 스택 안의 각 뷰들 간의 간격 조정하기
Stack() 안에 spacing : 하고 띄울 간격을 넣어주면 된다.
VStack(spacing: 100){
Rectangle()
.foregroundColor(.red)
.frame(width: 100, height: 100)
Rectangle()
.foregroundColor(.yellow)
.frame(width: 100, height: 100)
Rectangle()
.foregroundColor(.blue)
.frame(width: 100, height: 100)
또는 Spacer() 을 이용할 수도 있다. Spacer()을 넣으면 빈 공간을 만들어 쭉 밀어버리게 된다.
위 아래로 넣어서 갯수를 조절하면 해당 비율 만큼의 여백을 자동으로 생성한다. 또 .frame() 을 통해서 직접 크기를 조절해 줄 수도 있다.
VStack{
Spacer()
Rectangle()
.foregroundColor(.red)
.frame(width: 100, height: 100)
Rectangle()
.foregroundColor(.yellow)
.frame(width: 100, height: 100)
Spacer()
Rectangle()
.foregroundColor(.blue)
.frame(width: 100, height: 100)
Spacer()
}
.frame(width: 300)
.background(Color.green)
2) 내부 뷰들 정렬하기
Stack() 안에 alignment: 하고 정렬시킬 위치를 설정해 준다. (.leading, .trailing, .center, .top, .bottom)
그러면 해당 뷰 안에서만 움직이고 frame 안에서는 움직이지 않는다. 이를 해결하기 위해서는 스택 안에 Divider() 을 넣으면 된다. 다만 희미하게 Divider()의 선이 보일 수 있는데 이는 Divider()의 속성에 opacity() 를 0으로 주면 해결할 수 있다.
VStack(alignment: .leading, spacing: 100){
//Divider()
Rectangle()
.foregroundColor(.red)
.frame(width: 100, height: 100)
Rectangle()
.foregroundColor(.yellow)
.frame(width: 100, height: 100)
Rectangle()
.foregroundColor(.blue)
.frame(width: 200, height: 100)
}
.frame(width: 300)
.background(Color.green)
Divider() 추가
VStack(alignment: .leading, spacing: 100){
Divider()
.opacity(0)
Rectangle()
.foregroundColor(.red)
.frame(width: 100, height: 100)
Rectangle()
.foregroundColor(.yellow)
.frame(width: 100, height: 100)
Rectangle()
.foregroundColor(.blue)
.frame(width: 200, height: 100)
}
.frame(width: 300)
.background(Color.green)
3) ZStack
ZStack은 뷰들을 가로나 세로가 아닌 중첩해서 표시한다.
코드에서 아래로 내려갈수록 위에 덮이게 된다. 단 설정에서 zIndex()를 통해서 레벨을 (기본 0) 설정해 줄 수도 있다.
ZStack{
Rectangle()
.foregroundColor(.green)
.frame(width: 150, height: 150)
.zIndex(0)
Rectangle()
.foregroundColor(.red)
.frame(width: 100, height: 100)
.zIndex(0)
Rectangle()
.foregroundColor(.yellow)
.frame(width: 50, height: 50)
.zIndex(0)
}
zIndex 변경
ZStack{
Rectangle()
.foregroundColor(.green)
.frame(width: 150, height: 150)
.zIndex(0)
Rectangle()
.foregroundColor(.red)
.frame(width: 100, height: 100)
.zIndex(1) // zIndex 변경
Rectangle()
.foregroundColor(.yellow)
.frame(width: 50, height: 50)
.zIndex(0)
}
각 뷰들의 위치를 변경하려면 padding()이나 offset()를 활용할 수 있다.
ZStack{
Rectangle()
.foregroundColor(.green)
.frame(width: 150, height: 150)
Rectangle()
.foregroundColor(.red)
.frame(width: 100, height: 100)
.padding(.bottom, 50)
Rectangle()
.foregroundColor(.yellow)
.frame(width: 50, height: 50)
.offset(x: 50)
}
댓글
댓글 쓰기