SwiftUI - offset(x:y:)

백성준·2021년 1월 13일
0

SwiftUI

목록 보기
4/5

offset(x:y:)

Offset this view by the specified horizontal and vertical distances.

definition of offset from Apple.

Declaration

func offset(x: CGFloat = 0, y: CGFloat = 0) -> some View

Discussion

오프셋이란, 기준이 되는 주소에 더해지는 값을 의미한다. View 타입에 적용되는 이 메소드는 x, y 값 입력을 통해 해당 View 의 위치를 조정한다.

Text("Offset by passing horizontal & vertical distance")
    .border(Color.green)
    .offset(x: 20, y: 50)
    .border(Color.gray)

offset 에 의하여 위치가 변경되었으나, 기존의 주소는 유지되는 것을 2가지 색깔의 border 을 통하여 확인할 수 있다.

활용 방법

기본적인 활용 (with: Animation, Gesture)

struct OffsetView: View {
    @State var isShow: Bool = false
    
    var body: some View {
        VStack {
            Spacer()

            
            ZStack {
                ZStack {
                    Rectangle()
                        .foregroundColor(.white)
                        .frame(width: 250, height: 250)
                        .cornerRadius(20)
                        .shadow(color: .gray, radius: 10, x: 5, y: 5)
                        .overlay(Text("Hello, World!"))
                        .offset(x: 30)
                        
                }
                
                Image(uiImage: #imageLiteral(resourceName: "turtlerock"))
                    .cornerRadius(20)
                    .shadow(color: .gray, radius: 10, x: 5, y: 5)
                    .rotationEffect(Angle(degrees: isShow ? 40 : 0))
                    .offset(x: isShow ? -150 : 0, y: isShow ? -100 : 0)
                    .animation(.spring(response: 0.6, dampingFraction: 0.6))

            }
            .onTapGesture {
                isShow.toggle()
            }

                
    
            Spacer()
        }
    }
}

삼항연산자를 활용하여 offset 의 값이 조건에 따라 변화되도록 하였다. 이에 animation 을 적용하여 위와 같은 효과를 주었다.

profile
프로그래밍 전공 대학생

0개의 댓글