swift 设置导航栏(基础篇)

extension HomeViewController{
    private func setupNavigationBar(){
        /***
         设置导航栏背景颜色
         ***/
        navigationController?.navigationBar.barTintColor = UIColor.red
        /***
         设置导航栏title
         ***/
        //        self.title = "网易新闻"
        navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor : UIColor.white]
        // 自定义view设置title
        let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
        titleLabel.text = "网易新闻"
        titleLabel.textColor = UIColor.white
        navigationItem.titleView = titleLabel
        // 图片
        let imageView = UIImageView(image: UIImage(named : "contentview_imagebg_logo"))
        navigationItem.titleView = imageView
        /***
         设置导航栏左右按钮
         ***/
        //文字
        let leftBarButtonItem = UIBarButtonItem(title: "leftButton", style: .plain, target: self, action: #selector(self.leftClick))
        let rightBarButtonItem = UIBarButtonItem(title: "rightButton", style: .plain, target: self, action: #selector(self.rightClick))

        navigationItem.leftBarButtonItem = leftBarButtonItem
        navigationItem.rightBarButtonItem = rightBarButtonItem
        // 图片
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "fog"), style: .plain, target: self, action: #selector(self.leftClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "fog"), style: .plain, target: self, action: #selector(self.rightClick))
        // 自定义
        let leftButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
        let rightButton = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
        leftButton.setTitleColor(UIColor.black, for: UIControlState.normal)
        rightButton.setTitleColor(UIColor.black, for: UIControlState.normal)
        leftButton.setTitle("leftButton", for: UIControlState.normal)
        rightButton.setTitle("rightButton", for: UIControlState.normal)
        leftButton.addTarget(self, action: #selector(leftClick), for: UIControlEvents.touchUpInside)
        rightButton.addTarget(self, action: #selector(rightClick), for: UIControlEvents.touchUpInside)
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftButton)
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        // BarButtonItem颜色
        leftBarButtonItem.tintColor = UIColor.black
        
    }
    
    @objc private func leftClick() {
        print("leftClick")
    }
    
    @objc private func rightClick() {
        print("rightClick")
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容