How to Automatically Adjust Offset in SwiftUI When Resizing a Rectangle to Maintain Its Original Position?

The Issue in My Project:

In my SwiftUI project, I have a red rectangle whose size and position I want to control dynamically. The rectangle’s size is represented by a rect state variable, and its position is managed using an offset state variable. When I increase or decrease the rectangle’s width using buttons, the origin of the rectangle changes due to the size modification.

To maintain the rectangle’s visual position on the screen, I manually adjust the offset in the button actions. For example, if I add 20 points to the rectangle’s width, I also increase the offset.width to counteract the shift in its origin.

What I Want to Achieve:

I want to simplify this logic by automatically calculating the necessary offset adjustment within the .onChange modifier of the GeometryReader. The goal is to dynamically compute and update the offset whenever the frame of the rectangle changes, eliminating the need to manually adjust the offset in the button actions. This ensures that the rectangle stays visually stationary on the screen regardless of changes to its size.

Original code:

import SwiftUI

struct ContentView: View {
    
    @State private var rect: CGRect = CGRect(origin: .zero, size: CGSize(width: 200.0, height: 50.0))
    @State private var offset: CGSize = CGSize()
    
    var body: some View {
        
        VStack {
            Spacer()
            
            Rectangle()
                .fill(Color.blue)
                .frame(width: 200.0, height: 50.0)
            
            Rectangle()
                .fill(Color.red)
                .frame(width: rect.width, height: rect.height)
                .overlay(Text(String(describing: rect.origin) + String(describing: rect.size)).bold())
                .background(
                    GeometryReader { geometryValue in
                        Color.clear
                            .onAppear {
                                rect = geometryValue.frame(in: .global)
                            }
                            .onChange(of: geometryValue.frame(in: .global)) { newValue in
                                rect = newValue
                            }
                    }
                )
                .offset(offset)
                .animation(Animation.default, value: offset)
                .animation(Animation.default, value: rect.size.width)

            Spacer()
            
            HStack {
                Button("add width") {
                    rect.size.width += 20.0
                    offset.width += 10.0
                }
                
                Button("subtract width") {
                    rect.size.width -= 20.0
                    offset.width -= 10.0
                }
            }
            
        }
        .padding()
        
    }
}

Attempt to solve the issue:

The attempted approach does not solve the issue and also introduces a new animation problem. I prefer to use the animation modifier instead of withAnimation.

import SwiftUI

struct ContentView: View {
    
    @State private var rect: CGRect = CGRect(origin: .zero, size: CGSize(width: 200.0, height: 50.0))
    @State private var previousRect: CGRect = CGRect(origin: .zero, size: CGSize(width: 200.0, height: 50.0))
    @State private var offset: CGSize = CGSize()
    
    var body: some View {
        
        VStack {
            Spacer()
            
            Rectangle()
                .fill(Color.blue)
                .frame(width: 200.0, height: 50.0)
            
            Rectangle()
                .fill(Color.red)
                .frame(width: rect.width, height: rect.height)
                .overlay(Text(String(describing: rect.origin) + String(describing: rect.size)).bold())
                .background(
                    GeometryReader { geometryValue in
                        Color.clear
                            .onAppear {
                                rect = geometryValue.frame(in: .global)
                                previousRect = rect
                            }
                            .onChange(of: geometryValue.frame(in: .global)) { newValue in
                                let deltaX: CGFloat = newValue.origin.x - previousRect.origin.x
                                let deltaY: CGFloat = newValue.origin.y - previousRect.origin.y
                                
                                offset.width -= deltaX
                                offset.height -= deltaY
                                
                                previousRect = newValue
                                rect = newValue
                            }
                    }
                )
                .offset(offset)
                .animation(Animation.default, value: offset)
                .animation(Animation.default, value: rect.size.width)

            Spacer()
            
            HStack {
                Button("add width") {
                    rect.size.width += 20.0
                }
                
                Button("subtract width") {
                    rect.size.width -= 20.0
                }
            }
            
        }
        .padding()
        
    }
}

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật