繁体   English   中英

如何在 Swift 中为 leftBarButtonItem 和 rightBarButtonItem 设置不同的色调

[英]How to set different tint color for leftBarButtonItem and rightBarButtonItem in Swift

我尝试了很多解决方案,但没有按预期工作

根据我在每个 viewcontoller viewWillDisappear 中的应用程序结构,我们必须像下面的代码一样恢复导航栏

let textAttributes = [NSAttributedString.Key.foregroundColor: UIColor.black]
        navigationController?.navigationBar.tintColor = .blue
        navigationController?.navigationBar.backgroundColor = .white
        navigationController?.navigationBar.isTranslucent = false

        // Restore the navigation bar to default from transparent
        if #available(iOS 15, *) {
            let appearance = UINavigationBarAppearance()
            appearance.configureWithDefaultBackground()
            appearance.backgroundColor = .white 
            appearance.titleTextAttributes = textAttributes

            // Customizing our navigation bar
            navigationItem.standardAppearance = appearance
            navigationItem.scrollEdgeAppearance = appearance
        } else {
            navigationController?.navigationBar.titleTextAttributes = textAttributes
            navigationController?.navigationBar.setBackgroundImage(nil, for: .default)
            navigationController?.navigationBar.shadowImage = nil
        }

在其他视图控制器中,我需要添加具有不同颜色的leftBarButtonItemrightBarButtonItem ,但只有当我更改以上代码navigationBar.tinitColor时,它总是变为蓝色,我可以看到 navigationItem barbutton 中的颜色变化,但两者都是相同的颜色,这是我给出的导航栏.tinitColor

这是 rightBarButtonItem 色调颜色更改代码

let barButtonItem = UIBarButtonItem(title: "", style: .plain, target: self, action: nil)
        barButtonItem.tintColor = .black
        barButtonItem.accessibilityIdentifier = "navbar_notificationbutton"
        navigationItem.rightBarButtonItem = barButtonItem

实际结果截图

实际结果截图

预期结果截图

预期结果截图

提前致谢!!!

要为导航栏按钮更改或应用不同的色调颜色,您可以使用以下代码

    let backButton = UIButton(frame: CGRect(x: 0.0, y: 0.0, width: 44.0, height: 44.0))
    backButton.setImage(UIImage(systemName: "chevron.backward"), for: .normal)
    backButton.addTarget(self, action: #selector(btnBack), for: .touchUpInside)
    backButton.tintColor = .red
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)
    
    let notificationButton = UIButton(frame: CGRect(x: 0.0, y: 0.0, width: 44.0, height: 44.0))
    notificationButton.setImage(UIImage(systemName: "bell"), for: .normal)
    notificationButton.addTarget(self, action: #selector(btnShowNotifications), for: .touchUpInside)
    notificationButton.tintColor = .systemGreen
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: notificationButton)

在上面的代码中,我创建了一个back按钮并将其分配给leftBarButtonItem ,同样,我创建了另一个具有不同色调颜色的按钮并将其分配给rightBarButtonItem

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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