简体   繁体   中英

How to re-position Navigation Bar Buttons in SwiftUI

I have implemented the navigationBarTitle and I am trying to implement a navigationBarItem however the default position looks odd. 在此处输入图像描述

I want to be able to position the Next button in line with the navigationBarTitle . I was able to accomplish something with this code:

.navigationBarTitle(Text("Names"))
.navigationBarItems(trailing:
            Button(action: {
                print("tapped")
            }) {
                Group {
                    Text("Next")
                }.position(x: 0, y: 60).background(Color.purple)

            })

However the issue it that the button did not move, so it's not tappable where it displays Next. (I highlighted the position purple to demonstrate.) 在此处输入图像描述

Is there any way to accomplish this in a cleaner fashion? Or other methods or stacks that I could implement while keeping the navigationBarTitle Large Tile look in SwiftUI? Thank you!

You can wrap the button in a ZStack and position the Button inside of the ZStack like this:

import UIKit
import PlaygroundSupport
import SwiftUI

 struct ContentView: View {
    var body: some View {
        NavigationView {
            Text("Names")
                .navigationBarTitle(Text("Names"))
                .navigationBarItems(trailing:
                    ZStack {
                            Button(action: {
                                print("tapped")
                            }) {
                                Group {
                                    Text("Next")
                                }.background(Color.purple)
                            }.position(x: 0, y: 60)
                        })
        }
    }
}

let viewController = UIHostingController(rootView: ContentView())

PlaygroundPage.current.liveView = viewController

I tried it in the above playground example and it worked:

在此处输入图像描述

Edit:

This appears to make the button unresponsive unless you touch and drag:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM