繁体   English   中英

UIActivityViewController更改导航栏文本颜色

[英]UIActivityViewController Change Navigation Bar text color

我正在创建一个UIActivityViewController并尝试在点击共享消息图标后更改其文本颜色。

默认情况下,我在AppDelegate中将导航栏文本颜色设置为白色,就像这样

UINavigationBar.appearance().tintColor = whiteColor
UIBarButtonItem.appearance().tintColor = whiteColor

但是对于UIActivityViewController我想让它成为默认值(即黑色标题文本和蓝色Cancel按钮)

我试过以下没有运气:

let shareText = "text to share"
let activityViewController = UIActivityViewController(activityItems: [shareText], applicationActivities: [])

activityViewController.navigationController?.navigationBar.tintColor = UIColor.black
activityViewController.navigationController?.navigationItem.rightBarButtonItem?.tintColor = UIColor.blue

present(activityViewController, animated: true, completion: nil)

白色文本的结果仍然相同:

如果仔细查看图像,导航栏的标题和右侧栏按钮项目中都有白色文本。

在此输入图像描述

在iOS 11中,您可以通过设置更改“通过消息屏幕共享”中的取消按钮颜色:

UIButton.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).tintColor = .blue

对于试图做类似事情的其他人。 UIActivityViewController在完成时给我们回调。 我们可以做的是,更改UIBarButtonItem颜色,然后在完成时将其设置回原始颜色。

对我来说,完成处理程序没有正确地将颜色设置回原始颜色,所以我将不得不在viewWillAppear中执行此操作。

// Setting the required color for the bar buttons on share activities
UIBarButtonItem.appearance().setTitleTextAttributes([.foregroundColor: UIColor.yourRequiredColor], for: .normal)

// Re-setting the default color for the bar buttons again on activity's completion
activityViewController.completionWithItemsHandler = { (activityType, completed:Bool, returnedItems:[Any]?, error: Error?) in
    UIBarButtonItem.appearance().setTitleTextAttributes([.foregroundColor: UIColor.yourOriginalColor], for: .normal)
}

如果您在app delegate类中自定义导航栏,则应在共享操作(按下共享按钮等)之前更改它,但不要忘记在共享操作完成或解除时将其更改回来,因此您需要自定义在您共享操作的类的viewWillAppear func处的导航栏。

它应该是这样的:

class ShareActionViewController: UIViewController {

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //this should be same with your appDel settings:
        UINavigationBar.appearance().tintColor = .white
        UINavigationBar.appearance().barTintColor = .appPurpleColor
    }

    fileprivate func shareButtonPressed() {
        UINavigationBar.appearance().tintColor = .purple
        UINavigationBar.appearance().barTintColor = .white 
    }

}

我正在使用iOS 12,只是在我这样做时才工作:

static func setSystemNavigationBar() {
    UINavigationBar.appearance().tintColor = .black
    UINavigationBar.appearance().titleTextAttributes =
        [NSAttributedString.Key.foregroundColor : UIColor.black,
         NSAttributedString.Key.font: UIFont(name: "Aller", size: 20)!]
    UIBarButtonItem.appearance().setTitleTextAttributes([.foregroundColor: UIColor.blue], for: .normal)
}

您可以根据需要更改字体和颜色。

暂无
暂无

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

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