๐Ÿ‘”ViewPreference

๐Ÿ’พ ็จ‹ๅผ๏ผšhttps://github.com/lochiwei/ViewPreferences/tree/main

/*
 History:
 2021.??.?? - first version
 2022.01.18 + reportWidth, actOnWidth, actOnSelfWidth, ViewPreference.Width
 */

import SwiftUI

/// ๐Ÿ…ฟ๏ธ HasDefaultValue
public protocol HasDefaultValue {
    static var defaultValue: Self { get }
}

// ------------------------------------------
//     `HasDefaultValue` conforming types
// ------------------------------------------

/// ๐ŸŒ€ CGSize
extension CGSize: HasDefaultValue {
    public static var defaultValue: Self { .zero }
}

/// ๐ŸŒ€ CGRect
extension CGRect: HasDefaultValue {
    public static var defaultValue: Self { .zero }
}

/// ๐ŸŒ€ CGFloat
extension CGFloat: HasDefaultValue {
    public static var defaultValue: Self { .zero }
}

// -----------------------
//     ViewPreference
// -----------------------

/// ๐Ÿ”ธ ViewPreference
public enum ViewPreference {
    
    // ๅฐ‡ๆœ‰้—œ bounds anchor ็š„่ณ‡่จŠๆ”พๅˆฐ view extension methods ็š„ๅƒๆ•ธไธญ๏ผŒ
    // ็›ก้‡่ฎ“ method name ไธ่ฆๅคช้•ทใ€‚
    public enum BoundsAnchorType {
        case first
        case last
    }
    
    /// โญ ViewPreference type aliases
    public typealias Size = ViewPreference.First<CGSize>
    public typealias Width = ViewPreference.First<CGFloat>
    
    /// anchor preferences
    public typealias FirstBoundsAnchor = ViewPreference.FirstNonNil<Anchor<CGRect>>
    public typealias LastBoundsAnchor  = ViewPreference.LastNonNil<Anchor<CGRect>>
    
    /// ๐Ÿ”ธ ViewPreference.First
    public enum First<T: HasDefaultValue>: PreferenceKey {
        public typealias Value = T
        public static var defaultValue: Value { Value.defaultValue }
        public static func reduce(value: inout Value, nextValue: () -> Value) {
            // โญ ignore all values other than the first
        }
    }
    
    /// ๐Ÿ”ธ ViewPreference.FirstNonNil<T>
    public enum FirstNonNil<T>: PreferenceKey {
        public typealias Value = T?
        public static var defaultValue: Value { nil }
        public static func reduce(value: inout Value, nextValue: () -> Value) {
            value = value ?? nextValue()   // nil or first non-nil value
        }
    }
    
    /// ๐Ÿ”ธ ViewPreference.LastNonNil<T>
    public enum LastNonNil<T>: PreferenceKey {
        public typealias Value = T?
        public static var defaultValue: Value { nil }
        public static func reduce(value: inout Value, nextValue: () -> Value) {
            value = nextValue() ?? value   // nil or last non-nil value
        }
    }
}

History

2021.??.?? - first version
2022.01.18 + reportWidth, actOnWidth, actOnSelfWidth, ViewPreference.Width

Last updated