【发布时间】:2021-03-15 13:21:04
【问题描述】:
我尝试在swiftUI中修复按钮宽度,但是无论宽度是指向.frame(width: )还是固定在.fixedSize(horizontal: true, vertical: false)修饰符中,或者两者兼而有之,它仍然不起作用。该按钮只是按其内容长度缩小或扩大。我该如何解决?
请看下面的代码和图片:
struct ContentView: View {
var body: some View {
let days = [0, 1, 2, 3, 4]
let dayWeatherList = ["Sunday, Sunny",
"Monday, Sunny",
"Tuesday, Sunny",
"Wednesday, Sunny",
"Thursday, Sunny"]
let aqiList = [aqiItem(aqi: 6, color: .green),
aqiItem(aqi: 123, color: .orange),
aqiItem(aqi: 25, color: .green),
aqiItem(aqi: 345, color: .red),
aqiItem(aqi: 56, color: .yellow)]
VStack {
ForEach(days, id: \.self) { index in
let dayWeatherInfo = dayWeatherList[index]
let aqiForecast = aqiList[index]
ForecastDayView(dayWeatherInfo: dayWeatherInfo, aqiForecast: aqiForecast)
}
}
.padding(24)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
struct aqiItem {
let aqi: Int
let color: Color
}
struct ForecastDayView: View {
let dayWeatherInfo: String
let aqiForecast: aqiItem
var body: some View {
let fontSize: CGFloat = 14
HStack(alignment: .center) {
Text(dayWeatherInfo)
.font(.system(size: fontSize))
.fontWeight(.semibold)
.foregroundColor(.black)
Spacer()
Text("24/32°")
.font(.system(size: fontSize))
.fontWeight(.semibold)
.foregroundColor(.black)
Spacer()
HStack(spacing: 16) {
if let aqiForecast = aqiForecast {
let aqi = aqiForecast.aqi
let color = aqiForecast.color
Button(action: {}, label: {
Text("\(aqi)")
.foregroundColor(.white)
.padding(EdgeInsets(top: 2, leading: 4, bottom: 2, trailing: 4))
})
.font(.system(size: 13))
.background(color)
.cornerRadius(4)
.frame(width:40)
.fixedSize(horizontal: true, vertical: false)
}
let length: CGFloat = 18
Image("100")
.resizable()
.frame(width: length, height: length)
Image("101")
.resizable()
.frame(width: length, height: length)
}
}
}
}
提前非常感谢!
【问题讨论】:
-
您是否尝试过将 Button 标签放入 HStack 中?如果将 Spacers 放在任一侧,文本将保持居中,并且您可以控制 HStack 的宽度。