Adjust position of bar button item when using large titles with iOS 11

后端 未结 5 932
暗喜
暗喜 2021-02-05 06:32

I am using the large title navbar with iOS 11, but when I add a bar button item it looks weird positioned in the same location as the original title navbar. I would like to move

5条回答
  •  走了就别回头了
    2021-02-05 06:56

    If anyone is still looking how to do this in SwiftUI. I made a package named NavigationBarLargeTitleItems to deal with this. It mimics the behavior you see in the AppStore and Messages-app.

    In this example you will see a profile icon but you can also use text such as the Create Recipe-button. If you like to make it appear as a standard navigation bar item as soon as you scroll you need the GeometryReader for that. If you like an example please let me know.

    Please note to be able to accomplish this behavior we need to add to the '_UINavigationBarLargeTitleView' which is a private class and therefor might get your app rejected when submitting to the App Store.

    I'm also including the full relevant source code here for those who dislike links or just want to copy/paste.

    Extension:

    // Copyright © 2020 Mark van Wijnen
    // Permission is hereby granted, free of charge, to any person obtaining a copy
    // of this software and associated documentation files (the “Software”), to deal
    // in the Software without restriction, including without limitation the rights
    // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    // copies of the Software, and to permit persons to whom the Software is
    // furnished to do so, subject to the following conditions:
    //
    // The above copyright notice and this permission notice shall be included in
    // all copies or substantial portions of the Software.
    //
    // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    // SOFTWARE.
    import SwiftUI
    
    public extension View {
        func navigationBarLargeTitleItems(trailing: L) -> some View where L : View {
            overlay(NavigationBarLargeTitleItems(trailing: trailing).frame(width: 0, height: 0))
        }
    }
    
    fileprivate struct NavigationBarLargeTitleItems: UIViewControllerRepresentable {
        typealias UIViewControllerType = Wrapper
        
        private let trailingItems: L
        
        init(trailing: L) {
            self.trailingItems = trailing
        }
        
        func makeUIViewController(context: Context) -> Wrapper {
            Wrapper(representable: self)
        }
        
        func updateUIViewController(_ uiViewController: Wrapper, context: Context) {
        }
        
        class Wrapper: UIViewController {
            private let representable: NavigationBarLargeTitleItems?
            
            init(representable: NavigationBarLargeTitleItems) {
                self.representable = representable
                super.init(nibName: nil, bundle: nil)
            }
            
            required init?(coder: NSCoder) {
                self.representable = nil
                super.init(coder: coder)
            }
                    
            override func viewWillAppear(_ animated: Bool) {
                guard let representable = self.representable else { return }
                guard let navigationBar = self.navigationController?.navigationBar else { return }
                guard let UINavigationBarLargeTitleView = NSClassFromString("_UINavigationBarLargeTitleView") else { return }
               
                navigationBar.subviews.forEach { subview in
                    if subview.isKind(of: UINavigationBarLargeTitleView.self) {
                        let controller = UIHostingController(rootView: representable.trailingItems)
                        controller.view.translatesAutoresizingMaskIntoConstraints = false
                        subview.addSubview(controller.view)
                        
                        NSLayoutConstraint.activate([
                            controller.view.bottomAnchor.constraint(
                                equalTo: subview.bottomAnchor,
                                constant: -15
                            ),
                            controller.view.trailingAnchor.constraint(
                                equalTo: subview.trailingAnchor,
                                constant: -view.directionalLayoutMargins.trailing
                            )
                        ])
                    }
                }
            }
        }
    }
    

    Usage:

    import SwiftUI
    import NavigationBarLargeTitleItems
    
    struct ContentView: View {
        var body: some View {
            NavigationView {
                List {
                    ForEach(1..<50) { index in
                        Text("Sample Row \(String(index))")
                    }
                }
                .navigationTitle("Navigation")
                .navigationBarLargeTitleItems(trailing: ProfileIcon())
            }
        }
    }
    
    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }
    
    struct ProfileIcon: View {
        var body: some View{
            Button(action: {
                print("Profile button was tapped")
            }) {
                Image(systemName: "person.circle.fill")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .foregroundColor(.red)
                    .frame(width: 36, height: 36)
            }
            .offset(x: -20, y: 5)
        }
    }
    

    Preview

提交回复
热议问题