🌅 SystemImage

SwiftUI 1.0 中的 SF Symbols, 它們的 frame 沒有辦法包含整個圖形,這似乎是一個 bug,所以我們自己寫了這個 SystemImage 來修復這個問題。

SF Symbols 的 frame 沒有包住整個圖形 🐞

這似乎是 SwiftUI 1.0 (Xcode 11) 的 🐞,但在 SwiftUI 2.0 (Xcode 12) 據說修復了。 👉 Why the frame of an SF Symbol isn't encompassing its entire image? - StackOverflow

Workaround

/*
 Why the frame of an SF Symbol isn't encompassing its entire image?
 https://stackoverflow.com/a/63942841/5409815
 
 This appears to be a bug that is now fixed in SwiftUI 2.0 (Xcode 12).
 
 Here is a workaround for SwiftUI 1.0 (Xcode 11). 
 It uses UIImage(systemName:) to get the actual dimensions of the image, 
 and then uses .aspectRatio(_:contentMode:) to set the correct aspect ratio.
 */

import SwiftUI

/// # 🌅 SystemImage
/// SystemImage("heart.fill")
public struct SystemImage: View {
    
    // SF Symbol name
    let name: String
    
    // public init
    public init(_ name: String) {
        self.name = name
    }
    
    // view body
    public var body: some View {
        // ⭐️ use UIImage to get the actual size
        let size = UIImage(systemName: name)!.size
        return Image(systemName: name)
            .resizable()
            // set the correct aspect ratio for Image(systemName:)
            .aspectRatio(size, contentMode: .fit)
    }
}

參考資料

Last updated