首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >斯威夫特5: UINavigationController要到DetailsViewController才会出现

斯威夫特5: UINavigationController要到DetailsViewController才会出现
EN

Stack Overflow用户
提问于 2020-06-05 02:37:19
回答 1查看 173关注 0票数 1

我正在以编程的方式重建我的应用程序,而不是使用故事板,我的UINavigationController会遇到问题。当应用程序第一次加载根ViewController时,包含“载体”和时间的条形图是我指定的颜色的轻量级版本,搜索栏存在,而不是普通的导航栏。

当我点击/单击UITableView上的一个单元格以到达详细信息屏幕,然后返回时,我的UINavigationBar将正确显示,但搜索栏将消失。我肯定我混淆了什么东西,但我不知道我在哪里搞砸了,或者我是不是完全错过了什么。任何和所有的帮助都将不胜感激。我还包括了一个图片,作为一个例子,发生了什么。

Nonexistant UINavigationController > Detail screen > Back.gif

我在TabBarController SceneDelegate 中设置了一个

代码语言:javascript
运行
复制
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
// MARK: - Properties
var window: UIWindow?
let tabBarDelegate = TabBarDelegate()
let userAuthToken = UserDefaults.standard.string(forKey: "token")
let userKeyToken = UserDefaults.standard.string(forKey: "key")


func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    // Disable dark mode
    if #available(iOS 13.0, *) {
        window?.overrideUserInterfaceStyle = .light
    }

    // IF USER IS LOGGED IN
    if let windowScene = (scene as? UIWindowScene) {

        if let _ = userAuthToken {
            self.window = UIWindow(windowScene: windowScene)

            // CREATE TAB BAR //
            let tabController = UITabBarController()

            tabController.tabBar.backgroundColor = .white

            // Instantiate the storyboards
            let cannabisStoryboard = UIStoryboard(name: "Cannabis", bundle: nil)
            let profileStoryboard = UIStoryboard(name: "Profile", bundle: nil)


            // Instantiate the view controllers to storyboards
            let cannabisVC = cannabisStoryboard.instantiateViewController(withIdentifier: "Cannabis") as! CannabisViewController
            let profileVC = profileStoryboard.instantiateViewController(withIdentifier: "Profile") as! ProfileViewController

            // Displays the items in below order in tab bar
            let vcData: [(UIViewController, UIImage, UIImage)] = [
                (cannabisVC, UIImage(named: "Cannabis_icon")!, UIImage(named: "Cannabis_icon_selected")!),
                (profileVC, UIImage(named: "Profile_icon")!, UIImage(named: "Profile_icon_selected")!),
            ]

            let vcs = vcData.map { (vc, defaultImage, selectedImage) -> UINavigationController in
                let nav = UINavigationController(rootViewController: vc)
                nav.tabBarItem.image = defaultImage
                nav.tabBarItem.selectedImage = selectedImage

                return nav
            }

            // Assign to tab bar controller
            tabController.viewControllers = vcs
            tabController.tabBar.isTranslucent = false
            tabController.delegate = tabBarDelegate

            // Disables rendering for tab bar images
            if let items = tabController.tabBar.items {
                for item in items {
                    if let image = item.image {
                        item.image = image.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
                    }

                    if let selectedImage = item.selectedImage {
                        item.selectedImage = selectedImage.withRenderingMode(UIImage.RenderingMode.alwaysOriginal)
                    }

                    // Hides title
                    item.imageInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0)
                }
            }

            // Customize Navigation bar
            UINavigationBar.appearance().backgroundColor = UIColor(rgb: 0x00ffcc)

            // Disable dark mode
            window!.overrideUserInterfaceStyle = .light

            window?.rootViewController = tabController
            window?.makeKeyAndVisible()



        } else {
            // let loginStoryboard = UIStoryboard(name: "Login", bundle: nil)
            // let loginViewController = loginStoryboard.instantiateViewController(withIdentifier: "Login") as! LoginViewController

            // Disable dark mode
            window!.overrideUserInterfaceStyle = .light

            // window?.rootViewController = loginViewController
            window?.rootViewController = LoginViewController()
            window?.makeKeyAndVisible()
        }



        window?.windowScene = windowScene
    }

}

Root ViewController (简化为相关信息)

代码语言:javascript
运行
复制
class CannabisViewController: UIViewController {

// MARK:- Outlets
let tableView = UITableView()

// MARK:- Properties
var cannabisDetailViewController: CannabisDetailsViewController? = nil


// Search
let searchController = UISearchController(searchResultsController: nil)
var isSearchBarEmpty: Bool { return searchController.searchBar.text?.isEmpty ?? true }
var filteredStrains = [Cannabis]()
var isFiltering: Bool { return searchController.isActive && !isSearchBarEmpty }


// MARK: - ViewWillLayoutSubViews
override func viewWillLayoutSubviews() {
    let navigationBar: UINavigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 44))

    // navigationController?.setViewControllers([CannabisViewController()], animated: true)


    self.view.addSubview(navigationBar)
}

// MARK: - ViewDidLoad
override func viewDidLoad() {
    super.viewDidLoad()

    configurePage()


    // MARK: Self sizing table view cell
    tableView.estimatedRowHeight = CGFloat(88.0)
    tableView.rowHeight = UITableView.automaticDimension



    // MARK: DataSource/Delegate
    tableView.dataSource = self
    tableView.delegate = self


    // Removes default lines from table views
    tableView.tableFooterView = UIView()
    tableView.separatorStyle = .none


    // MARK: Navigation: logo in center
    let logoHeader = UIImageView(image: UIImage(named: "logoHeader"))
    self.navigationItem.titleView = logoHeader


    // MARK: API
    getCannabisList()


    // MARK: Search bar controller
    searchController.searchResultsUpdater = self
    searchController.obscuresBackgroundDuringPresentation = false
    searchController.searchBar.placeholder = "Search for a strain!"
    navigationItem.searchController = searchController
    definesPresentationContext = true

}


// Configure TableView
func configurePage() {
    // Configure Tableview
    view.addSubview(tableView)
    tableView.anchor(top: view.topAnchor, left: view.leftAnchor,
                     bottom: view.bottomAnchor, right: view.rightAnchor)
}

}

SearchController (仍在根ViewController中)

代码语言:javascript
运行
复制
    func updateSearchResults(for searchController: UISearchController) {
    let searchBar = searchController.searchBar
    let userSearch = searchBar.text!.trimmingCharacters(in: .whitespaces)
    search(searchText: userSearch)
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-05 03:20:57

我可以在这里看到几个问题,但是首先要在SceneDelegate中初始化窗口,您可以使用UIWindowScene

代码语言:javascript
运行
复制
var window: UIWindow?

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    guard let windowScene = (scene as? UIWindowScene) else { return }
    let window = UIWindow(windowScene: windowScene)
    self.window = window
    let rootViewController = RootViewController()
    window.rootViewController = UINavigationController(rootViewController: rootViewController)
    window.makeKeyAndVisible()
}

如果您想在应用程序中全局禁用黑暗模式,只需将一个键UIUserInterfaceStyle添加到Info.plist中,并将其值设置为Dark (或Light)。通过这样做,您将不需要更新每个视图控制器,因为它将覆盖全局应用程序默认样式。我强烈鼓励你增加对黑暗模式的支持!

如果要更改导航栏外观:

代码语言:javascript
运行
复制
if #available(iOS 13.0, *) {
    let navigationAppearance = UINavigationBarAppearance()
    navigationAppearance.configureWithOpaqueBackground()
    navigationAppearance.backgroundColor = .white
    navigationAppearance.titleTextAttributes = // ...
    navigationAppearance.largeTitleTextAttributes = // ...
    UINavigationBar.appearance().tintColor = .systemBlue
    UINavigationBar.appearance().barTintColor = .white
    UINavigationBar.appearance().standardAppearance = navigationAppearance
    UINavigationBar.appearance().scrollEdgeAppearance = navigationAppearance
} else {
    UINavigationBar.appearance().backgroundColor = .white
    UINavigationBar.appearance().barTintColor = .white
    UINavigationBar.appearance().tintColor = .systemBlue
    UINavigationBar.appearance().titleTextAttributes = // ...
    UINavigationBar.appearance().largeTitleTextAttributes = // ...
}

我做了一个最小的项目,让您看到一个使用搜索栏的工作示例,在这个示例中,状态栏的闪烁不会发生,UISearchBar的隐藏/显示动画在推送/弹出DetailViewController时正常工作。

RootViewController:

代码语言:javascript
运行
复制
import UIKit

class RootViewController: UIViewController {

    private let reuseIdentifier = "reuseIdentifier"

    lazy var tableView: UITableView = {
        $0.delegate = self
        $0.dataSource = self
        $0.register(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifier)
        return $0
    }(UITableView(frame: .zero, style: .grouped))

    private lazy var searchController: UISearchController = {
        $0.searchResultsUpdater = self
        $0.delegate = self
        $0.searchBar.delegate = self
        $0.obscuresBackgroundDuringPresentation = false
        $0.hidesNavigationBarDuringPresentation = false
        $0.searchBar.backgroundColor = .white
        $0.searchBar.tintColor = .systemBlue
        return $0
    }(UISearchController(searchResultsController: nil))

    override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
        setupConstraints()
    }

    func setupViews() {
        title = "Source"
        view.backgroundColor = .white
        navigationItem.searchController = searchController
        navigationItem.hidesSearchBarWhenScrolling = false
        view.addSubview(tableView)
        // ...
    }

    func setupConstraints() {
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        tableView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        tableView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    }
}

extension RootViewController: UITableViewDelegate {

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let detailViewController = DetailViewController()
        navigationController?.pushViewController(detailViewController, animated: true)
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
}

extension RootViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
        cell.textLabel?.text = "Cell at indexPath \(indexPath)"
        return cell
    }
}

extension RootViewController: UISearchResultsUpdating, UISearchControllerDelegate, UISearchBarDelegate {
    func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {}
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {}
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {}
    func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {}
    func updateSearchResults(for searchController: UISearchController) {}
}

DetailViewController:

代码语言:javascript
运行
复制
class DetailViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Detail"
        view.backgroundColor = .systemGray6
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62207213

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档