view.actOnSelfWidth()

import SwiftUI

extension View {
    /// โญ usage: `view.actOnSelfWidth { width in ... }`
    public func actOnSelfWidth(
        action: @escaping (CGFloat) -> Void
    ) -> some View
    {
        self.background( GeometryReader { geo in
            Color.clear
                // โญ ไธ‹ๅฑคๅ›žๅ ฑ่‡ชๅทฑ็š„ width
                .preference(key: ViewPreference.Width.self, value: geo.size.width)
        })
        // โญ ไธŠๅฑคๅพ—็Ÿฅ width๏ผŒไธฆ็”จ `action` ่™•็†ใ€‚
        .onPreferenceChange(ViewPreference.Width.self, perform: action)
    }
}

Last updated