.onChangeSize()

SwiftUI โŸฉ Views โŸฉ View โŸฉ .onChangeSize()

ๅŽŸๅ็‚บ๏ผš .readSize()๏ผŒไฝ†ๅ› ็‚บๆญคๆ–นๆณ•็š„ onChange closure ๆ˜ฏๅœจ frame size ๆœ‰ๆ”น่ฎŠๆ™‚ๆ‰ๆœƒ่งธ็™ผ๏ผŒไนŸๅฐฑๆ˜ฏ size ๆฒ’ๆ”น่ฎŠๆ™‚๏ผŒไธๆœƒๆœ‰ไปปไฝ•ๅๆ‡‰๏ผŒๅ› ๆญคไนŸไธๆœƒ็œŸ็š„ๅŽปๅŸท่กŒ "read size" ็š„ๅ‹•ไฝœ๏ผŒๆ‰€ไปฅๆ”นๅ็‚บ .onChangeSize() ๆ‰็ฌฆๅˆ็จ‹ๅผ็š„ๅŽŸๆ„๏ผŒไนŸๆ‰ไธๆœƒ่ชค็”จใ€‚

// 2022.02.15 (*) original name: `readSize`
// 2022.02.18 (r) renamed `onChangeSize`

extension View {
    /// get parent's offered size.
    /// ```
    /// view.onChangeSize { size in ... }
    /// ```
    func onChangeSize(onChange: @escaping (CGSize) -> Void) -> some View {
        background( GeometryReader { geo in
            Color.clear.preference(key: SizePreferenceKey.self, value: geo.size)
        }).onPreferenceChange(SizePreferenceKey.self, perform: onChange)
    }
}

private struct SizePreferenceKey: PreferenceKey {
    static var defaultValue: CGSize = .zero
    static func reduce(value: inout CGSize, nextValue: () -> CGSize) {}
}

Last updated