我正在尝试增加
Menu
内每个按钮的文本大小。这是我尝试更改文本大小的游乐场:
import SwiftUI
import PlaygroundSupport
struct Sample: View {
@State var selectedIndex = 0
private var inputs = [1, 2, 3, 4, 5]
var body: some View {
ZStack {
Text(String(inputs[selectedIndex]))
.font(.system(size: 30))
Menu {
ForEach(0 ..< inputs.count, id: \.self) {
let index = $0
let text = "\(inputs[index])"
Button(action: {
selectedIndex = index
}, label: {
Text(text)
.font(.system(size: 30))
})
}
} label: {
Label("", image: "")
.labelStyle(TitleOnlyLabelStyle())
.frame(maxWidth: .infinity, maxHeight: .infinity) // That way we have the same touch area.
}
}
.frame(width: 500, height: 500)
}
}
PlaygroundPage.current.setLiveView(Sample())
但是,设置文本元素本身的字体大小不会改变它:
Text(text)
.font(.system(size: 30))
是否有任何技巧/其他解决方案来增加每个元素的文本大小?
“Menu”组件及其子组件使用系统提供的默认样式进行渲染,该样式不能被覆盖。我建议你创建一个自定义的 MenuView,例如:
struct CustomMenu: View {
let items: [String]
let onSelect: (String) -> Void
@Binding var isExpanded: Bool
var body: some View {
VStack(alignment: .leading, spacing: 10) {
ForEach(items, id: \.self) { item in
Button(action: {
self.onSelect(item)
self.isExpanded.toggle()
}) {
Text(item)
.font(.system(size: 60)) // Set your custom font size here
.foregroundColor(.black)
}
}
}
.padding()
.background(Color.white)
.cornerRadius(5)
.shadow(radius: 5)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
你可以这样使用它:
struct Sample: View {
@State private var selectedIndex: Int = 0
@State private var isMenuExpanded: Bool = false
private var inputs = ["1", "2", "3", "4", "5"]
var body: some View {
VStack {
Button(action: {
self.isMenuExpanded.toggle()
}) {
HStack {
Text("Select Option")
.font(.system(size: 20))
Image(systemName: "arrow.down")
.rotationEffect(.degrees(isMenuExpanded ? 180 : 0))
}
}
if isMenuExpanded {
CustomMenu(items: inputs, onSelect: { selectedItem in
if let index = inputs.firstIndex(of: selectedItem) {
selectedIndex = index
}
}, isExpanded: $isMenuExpanded)
}
Spacer()
Text("Selected: \(inputs[selectedIndex])")
.font(.system(size: 30))
}
.padding().frame(width: 500, height: 500)
}
}