20 C
London
Monday, September 16, 2024

ios – Disable empty rectangle when lengthy touching again button – NavigationBar


That isn’t a easy rectangle. That’s truly a menu to point out the navigation stack. It is going to have extra buttons should you navigate deeper. This cannot be eliminate with regular APIs however you will get round it wit some swizzling:

  1. Implement this:
personal func swizzle(
    targetClass: AnyClass,
    originalSelector: Selector,
    swizzledSelector: Selector
) {
    let originalMethod = class_getInstanceMethod(targetClass, originalSelector)
    let swizzledMethod = class_getInstanceMethod(targetClass, swizzledSelector)
    method_exchangeImplementations(originalMethod!, swizzledMethod!)
}

extension UIViewController {
    static let classInit: Void = {
        let originalSelector = #selector(viewWillAppear(_:))
        let swizzledSelector = #selector(swizzledViewWillAppear(_:))
        swizzle(
            targetClass: UIViewController.self,
            originalSelector: originalSelector,
            swizzledSelector: swizzledSelector
        )
    }()

    @objc func swizzledViewWillAppear(_ animated: Bool) {
        if #out there(iOS 14.0, *) {
            let backButton = BackBarButtonItem(title: "", type: .plain, goal: nil, motion: nil)
            navigationItem.backBarButtonItem = backButton
        }
        swizzledViewWillAppear(animated)
    }
}

class BackBarButtonItem: UIBarButtonItem {
    @out there(iOS 14.0, *)
    override var menu: UIMenu? {
        get { tremendous.menu }
        set { }
    }
}
  1. Name UIViewController.classInit some the place early (just like the init of a view):
struct SomeView: View {
    init() {
        UIViewController.classInit
    }

    ,,,
}

Demo


💡 Maintain the menu with a workaround

As a substitute of above technique, you may set the right navigation title title onDisappear to make it work as anticipated:

struct NavigationTesting: View {
    @State var title: LocalizedStringKey = " "

    var physique: some View {
        NavigationStack {
            NavigationLink("Subsequent") {
                Textual content("View 2")
            }
            .navigationTitle(title)
            .onDisappear { title = "Web page 1" }
            .onAppear { title = " " }
        }
    }
}

This fashion you may populate the menu with the right title and conserving the “again” title hidden as meant.

Demo

Latest news
Related news

LEAVE A REPLY

Please enter your comment!
Please enter your name here