🔸ideal size
╱🚧 under construction
SwiftUI ⟩ view ⟩ layout ⟩ size ⟩ ideal
ideal size (🚧)
🚧
雖然 .frame(minWidth:idealWidth ...) 可以用來宣告 ideal size,但必須搭配 .fixedSize() 才會真正發生作用❗️
TestIdealSizeView - source code for the YouTube video above.

/*
Intrinsic Content Size (ideal size):
------------------------------------
🔸 1. define ideal size (SwiftUI won't respect it at first).
🔸 2. use `.fixedSize()` to respect ideal size.
🔸 3. use `.frame(width:height:) to override.
🔸 4. can mix (2) / (3)
*/
struct ContentView: View {
var body: some View {
VStack {
rect()
.fixedSize() // ⭐️ 2. respect ideal width/height
rect(.blue) // ⭐️ 2. respect ideal height
.fixedSize(horizontal: false, vertical: true)
rect(.orange) // ⭐️ 2. respect ideal width
.fixedSize(horizontal: true, vertical: false)
rect(.purple) // ⭐️ 3. override both
.frame(width: 150, height: 20)
rect(.green) // ⭐️ 4. respect height, override width
.fixedSize(horizontal: false, vertical: true)
.frame(width: 200)
}.padding()
}
}
extension ContentView {
func rect(_ color: Color = .pink) -> some View {
Rectangle()
.frame(idealWidth: 100, idealHeight: 100) // 1.
.foregroundColor(color)
}
}
SwiftUI ⟩
View ⟩
.fixedSize():Fixes view at its ideal size. (both width and height)
.fixedSize(horizontal:vertical:):Fixes view at its ideal size in the specified dimensions.
Layout ⟩
.frame(width:height:alignment:) - change proposed size.
.frame(minWidth:idealWidth:maxWidth ...) - define ideal size.
fixedSize(), fixedSize(horizontal:vertical:) - respect ideal size.
Last updated
Was this helpful?