SwiftUI设置VStack左对齐后内容仍居中该如何解决
问题原因
你给VStack设置的alignment: .leading仅控制VStack内部子视图的对齐规则,而你后续调用.frame(maxWidth: .infinity)时没有指定对齐参数,SwiftUI默认会将VStack视图整体在撑满的宽度范围内居中,VStack自身的宽度刚好适配内容宽度,所以整体看起来文本是居中的,和左右内边距无关。
解决方案
修改frame方法,添加alignment: .leading参数,让VStack在撑满父容器宽度的同时,自身内容靠左侧排布:
struct SortRow: View { var sortType: SortType @AppStorage(sortKey) var currentSorting: SortType = .winOrLoss var body: some View { VStack(alignment: .leading, spacing: 12) { Text(sortType.name) .multilineTextAlignment(.leading) .font(.system(size: 15.0)) .foregroundColor(Color(sortType == currentSorting ? UIColor.white : UIColor.systemGray2)) Text(sortType.detail) .multilineTextAlignment(.leading) .font(.system(size: 13.0)) .foregroundColor(Color(sortType == currentSorting ? UIColor.white : UIColor.systemGray)) } // 仅修改这一行,添加alignment参数 .frame(maxWidth: .infinity, alignment: .leading) .padding(12) .background(Color(sortType == currentSorting ? UIColor.systemGreen : UIColor.systemBackground)) } }
修改后VStack会撑满父容器的全部宽度,内部内容按左对齐排列,即可实现预期效果。
内容的提问来源于stack exchange,提问作者Kelton
相关产品推荐
相关产品推荐

