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")
    }
}
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容