[英]NavigationLink keeps aligning my text elements to center instead of leading SwiftUI
I have a CustomSearchBar
view that looks like this我有一个看起来像这样的CustomSearchBar
视图
However, when I wrap it with NavigationLink
, the placeholder text will be centered.但是,当我用NavigationLink
包装它时,占位符文本将居中。 And user inputs will be centered too.用户输入也将居中。
How do I maintain the leading alignment while using NavigationLink
?使用NavigationLink
如何保持领先对齐?
My code structure looks like this:我的代码结构如下所示:
enum Tab {
case social
}
struct MainAppView: View {
@State var selection: Tab = .social
var body: some View {
TabView(selection: $selection) {
ZStack{
CustomButton()
NavigationView { SocialView() }
}.tabItem{Image(systemName: "person.2")}.tag(Tab.social)
// other tabs....
}
struct SocialView: View {
// ...
var body: some View {
GeometryReader{ geometry in
VStack{
NavigationLink(destination: Text("test")) {
CustomSearchBar()
//...
}.navigationBarHidden(true)
.navigationBarTitle(Text(""))
}
}
}
}
struct CustomSearchBar: View {
var body: some View {
VStack{
HStack {
SearchBarSymbols(// some binding arguments)
CustomTextField(// some binding arguments)
CancelButton(// some binding arguments)
}
.padding(.vertical, 8.0)
.padding(.horizontal, 10.0)
.background(Color("SearchBarBackgroundColor"))
.clipShape(Capsule())
}
.padding(.horizontal)
}
}
struct CustomTextField: View {
var body: some View {
TextField("friend name", text: $searchText)
.frame(alignment: .leading)
.onTapGesture {
// some actions
}
.foregroundColor(Color("SearchBarSymbolColor"))
.accentColor(Color("SearchBarSymbolColor"))
.disableAutocorrection(true)
}
}
The issues with your code are:您的代码存在的问题是:
Solution:解决方案:
Move the navigation view below the text field, so that the new view will appear without covering it.将导航视图移动到文本字段下方,这样新视图就会出现而不会覆盖它。 Then change the navigation link so that it is activated via a binding that gets triggered when the search field is editing:然后更改导航链接,以便通过在编辑搜索字段时触发的绑定激活它:
struct SocialView: View {
@State private var text: String = ""
@State private var isActive: Bool = false
var body: some View {
GeometryReader{ geometry in
VStack {
CustomTextField(searchText: $text, isActive: $isActive)
.padding(.vertical, 8.0)
.padding(.horizontal, 10.0)
.background(Color("SearchBarBackgroundColor"))
.clipShape(Capsule())
NavigationView {
NavigationLink(isActive: $isActive, destination: { Text("test") }, label: { EmptyView() })
}
}
}
}
}
struct CustomTextField: View {
@Binding var searchText: String
@Binding var isActive: Bool
var body: some View {
TextField("friend name", text: $searchText) { editing in
self.isActive = editing
} onCommit: {
}
.frame(alignment: .leading)
.disableAutocorrection(true)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.