如何在SwiftUI中将按钮对齐至屏幕底部且中间视图保持居中
问题:将按钮固定在屏幕底部,中间视图居中显示
希望将按钮对齐至屏幕底部,同时让包含日期选择器的较大视图保持在屏幕中间。尝试使用.frame()修饰符和Spacer实现但未成功,当前代码及界面效果如下:

原始代码
ZStack { BackgroundView() VStack { VStack { DatePicker("Choose", selection: $selectedDate, displayedComponents: .date) DatePicker("Bedtime", selection: $bedtime, displayedComponents: .hourAndMinute) DatePicker("Waking up time", selection: $wakingUp, displayedComponents: .hourAndMinute) InfoText(timeInterval: timeInterval) .font(.title2) .fontWeight(.medium) .foregroundStyle(.white) .frame(maxWidth: .infinity) .padding(.vertical, 15) } .padding() .background(.gray.opacity(0.1)) .clipShape(RoundedRectangle(cornerRadius: 20)) .overlay( RoundedRectangle(cornerRadius: 20) .strokeBorder(lineWidth: 2) .foregroundStyle(.gray.opacity(0.5)) ) .padding() Button {} label: { Text("Sleep guidelines by age") .bold() .foregroundStyle(.purple) .padding() .background(.purple.opacity(0.1)) .clipShape(RoundedRectangle(cornerRadius: 20)) .overlay( RoundedRectangle(cornerRadius: 20) .stroke(lineWidth: 2) .foregroundStyle(.purple.opacity(0.6)) ) .shadow(color: .white.opacity(0.3), radius: 15) } } }
解决方案
核心是让外层VStack占满整个屏幕空间,通过Spacer()分配布局权重:
- 给外层
VStack添加.frame(maxWidth: .infinity, maxHeight: .infinity),使其充满屏幕 - 在中间视图上方加
Spacer(),将视图推至垂直居中位置 - 在中间视图和按钮之间加
Spacer(),将按钮推至屏幕底部
修改后的代码
ZStack { BackgroundView() VStack { // 顶部Spacer,把中间视图向下推到居中位置 Spacer() VStack { DatePicker("Choose", selection: $selectedDate, displayedComponents: .date) DatePicker("Bedtime", selection: $bedtime, displayedComponents: .hourAndMinute) DatePicker("Waking up time", selection: $wakingUp, displayedComponents: .hourAndMinute) InfoText(timeInterval: timeInterval) .font(.title2) .fontWeight(.medium) .foregroundStyle(.white) .frame(maxWidth: .infinity) .padding(.vertical, 15) } .padding() .background(.gray.opacity(0.1)) .clipShape(RoundedRectangle(cornerRadius: 20)) .overlay( RoundedRectangle(cornerRadius: 20) .strokeBorder(lineWidth: 2) .foregroundStyle(.gray.opacity(0.5)) ) .padding() // 中间Spacer,把按钮推到屏幕底部 Spacer() Button {} label: { Text("Sleep guidelines by age") .bold() .foregroundStyle(.purple) .padding() .background(.purple.opacity(0.1)) .clipShape(RoundedRectangle(cornerRadius: 20)) .overlay( RoundedRectangle(cornerRadius: 20) .stroke(lineWidth: 2) .foregroundStyle(.purple.opacity(0.6)) ) .shadow(color: .white.opacity(0.3), radius: 15) } // 给按钮加底部内边距,避免紧贴屏幕边缘 .padding(.bottom) } // 让外层VStack充满整个屏幕 .frame(maxWidth: .infinity, maxHeight: .infinity) }
修改后,中间的日期选择器视图会保持在屏幕垂直居中位置,按钮固定在屏幕底部,同时底部内边距避免了按钮紧贴屏幕边缘的问题。
内容的提问来源于stack exchange,提问作者burak
相关产品推荐
相关产品推荐

