UIBarButtonItem以编程方式更改颜色

时间:2020-03-10 17:47:39

标签: swift swift5 xcode11

我剩下的UIBarButtonItem就像开关一样,因此我想在关闭时将其设置为灰色,在打开时将其设置为正常的色调,但我不知道如何实现

以下是用于分配按钮的代码:

    doneHomeworksButton = UIBarButtonItem(image: doneHomeworksButtonImage, style: .plain, target: self, action: #selector(doneHomeworksClicked))
    addButton = UIBarButtonItem(image: plusButtonImage, style: .plain, target: self, action: #selector(plusButtonClicked))

    self.navigationItem.rightBarButtonItem = addButton
    self.navigationItem.leftBarButtonItem = doneHomeworksButton

这是模拟器(我想更改左侧按钮)

1 个答案:

答案 0 :(得分:1)

这是我使用文本而不是图标的方式。您可以使用fontawesome或任何其他的FM符号。而且,当单击按钮时,您也可以更改图像

class ViewController: UIViewController{


var btnTick:UIBarButtonItem?


override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
    btnTick  = UIBarButtonItem(title: "2", style: .plain, target: self, action: #selector(didClickedBtn(_ :)))
    btnTick?.tintColor = .blue
    navigationItem.leftBarButtonItem = btnTick
}

@objc func didClickedBtn(_ sender : UIBarButtonItem){
    sender.tintColor = .red
    view.layoutIfNeeded()
}

}

enter image description here

enter image description here