SwiftUI 如何对齐文本与使用条款、隐私政策按钮并支持应用内跳转
解决方案
问题根因
你当前将普通文本和按钮全部放在同一个HStack中实现,默认HStack仅支持单行元素横向排布,不会自动处理文本换行,且元素默认垂直对齐规则是居中对齐,不是和文本基线对齐,所以会出现按钮和文本错位、整行内容超出屏幕的问题。
推荐实现方案(iOS 15+ 适用)
不需要把完整文本拆成多个Text和Button的组合,保留你之前的富文本写法,只需拦截链接点击事件,替换为应用内Safari打开逻辑即可,完全保留原有的文本排版、自动换行、对齐效果,示例代码如下:
Text("继续操作即表示你同意我们的[服务条款(EULA)](https://www....),且确认你已阅读我们的[隐私政策](https://...).") .font(.system(size: 10)) .environment(\.openURL, OpenURLAction { url in // 拦截链接点击,自定义处理逻辑 if url.absoluteString == "服务条款对应的链接" { showTermsOfUse.toggle() } else if url.absoluteString == "隐私政策对应的链接" { showPrivacyPolicy.toggle() } return .handled // 告知系统无需再处理该链接跳转 }) .fullScreenCover(isPresented: $showTermsOfUse, content: { SFSafariViewWrapper(url: URL(string: "https://www....")!) }) .fullScreenCover(isPresented: $showPrivacyPolicy, content: { SFSafariViewWrapper(url: URL(string: "https://.....")!) })
低版本兼容方案
如果需要支持iOS 15以下的系统,可以调整你现有HStack的对齐规则,指定元素按文本基线对齐,同时允许文本自动换行,修改后的代码如下:
// 指定HStack按第一行文本基线对齐,移除默认间距 HStack(alignment: .firstTextBaseline, spacing: 0) { Text("继续操作即表示你同意我们的 ") .font(.system(size: 10)) .fixedSize(horizontal: false, vertical: true) // 允许文本多行显示 Button(action: { showTermsOfUse.toggle() }) { Text("服务条款(EULA)") .font(.system(size: 10)) .foregroundColor(.primary) .fixedSize(horizontal: false, vertical: true) } .fullScreenCover(isPresented: $showTermsOfUse, content: { SFSafariViewWrapper(url: URL(string: "https://www....")!) }) Text(",且确认你已阅读我们的") .font(.system(size: 10)) .foregroundColor(.primary) .fixedSize(horizontal: false, vertical: true) Button(action: { showPrivacyPolicy.toggle() }) { Text("隐私政策。") .font(.system(size: 10)) .foregroundColor(.primary) .fixedSize(horizontal: false, vertical: true) } .fullScreenCover(isPresented: $showPrivacyPolicy, content: { SFSafariViewWrapper(url: URL(string: "https://.....")!) }) }
如果需要支持整段文本自动换行,可将HStack替换为自定义的流式布局即可。
内容的提问来源于stack exchange,提问作者Arturo
相关产品推荐
相关产品推荐

