我尝试在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)
}
}
}
}按钮具有不同的宽度:

非常感谢提前!
发布于 2020-12-03 23:00:09
在设置宽度之前,您正在应用.background。如果您首先应用.frame(宽度: 40),然后设置.background颜色,您将看到所有内容都具有相同的大小。
Button(action: {}, label: {
Text("\(aqi)")
.foregroundColor(.white)
.padding(EdgeInsets(top: 2, leading: 4, bottom: 2, trailing: 4))
})
.frame(width:40)
.font(.system(size: 13))
.background(color)
.cornerRadius(4)
发布于 2020-12-03 23:38:33
修饰符的顺序很重要。此链接可能会对您有所帮助。
https://www.hackingwithswift.com/books/ios-swiftui/why-modifier-order-matters
按照davidev的建议操作,或者在文本上使用.frame(minWidth:40)并删除其水平填充。
Button(action: {}, label: {
Text("\(aqi)")
.foregroundColor(.white)
.padding(.vertical, 2)
.frame(minWidth:40)
})
.font(.system(size: 13))
.background(color)
.cornerRadius(4)https://stackoverflow.com/questions/65127462
复制相似问题