Code that reproduces the issue
import SwiftUI
@main
struct KeyboardLayoutProblemApp: App {
var body: some Scene {
WindowGroup {
iOSTabView()
}
}
}
struct iOSTabView: View {
var body: some View {
TabView {
GameView()
.frame(maxWidth: UIScreen.main.bounds.width, maxHeight: UIScreen.main.bounds.height)
.tabItem {
Label("Play", systemImage: "gamecontroller.fill")
}
}
}
}
struct GameView: View {
var body: some View {
VStack {
Text("Play")
Spacer()
KeyboardView()
}
.padding()
}
}
struct KeyboardView: View {
let firstRowLetters = "qwertyuiop".map { $0 }
let secondRowLetters = "asdfghjkl".map { $0 }
let thirdRowLetters = "zxcvbnm".map { $0 }
var body: some View {
VStack {
HStack {
ForEach(firstRowLetters, id: \.self) {
LetterKeyView(character: $0)
}
}
HStack {
ForEach(secondRowLetters, id: \.self) {
LetterKeyView(character: $0)
}
}
HStack {
ForEach(thirdRowLetters, id: \.self) {
LetterKeyView(character: $0)
}
}
}
.padding()
}
}
struct LetterKeyView: View {
let character: Character
var width: CGFloat { height*0.8 }
@ScaledMetric(relativeTo: .title3) private var height = 35
var body: some View {
Button {
print("\(character) pressed")
} label: {
Text(String(character).capitalized)
.font(.title3)
.frame(width: self.width, height: self.height)
.background {
RoundedRectangle(cornerRadius: min(width, height)/4, style: .continuous)
.stroke(.gray)
}
}
.buttonStyle(PlainButtonStyle())
}
}
Problem
GameView
doesn't fit its parent view:
Question
How do I make GameView
be at most as big as its parent view?
What I've tried and didn't work
GameView()
.frame(maxWidth: .infinity, maxHeight: .infinity)
GeometryReader { geometry in
GameView()
.frame(maxWidth: geometry.size.width, maxHeight: geometry.size.height)
}
GameView()
.clipped()
GameView()
.layoutPriority(1)
GameView()
.scaledToFit()
GameView()
.minimumScaleFactor(0.01)
GameView()
.scaledToFill()
.minimumScaleFactor(0.5)
I'm not using UIScreen.main.bounds.width
because I'm trying to build a multi-platform app.