swift - 当UI Switch在导航栏中更改时更改标题中的标签

时间:2017-10-28 13:23:37

标签: swift xcode

我想更改标题中的标签以与我的UISwitch相关联 虽然我还没有成功?

setLeftNavButton()

中调用

viewDidLoad()

func setLeftNavButton() {

    let switchControl=UISwitch()

    //switchControl.isOn = true
    //switchControl.setOn(true, animated: false)
    switchControl.addTarget(self, action: #selector(switchValueDidChange), for: .valueChanged)
    self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: switchControl)

   self.switchControl = switchControl

}

var switchControl: UISwitch?

func switchValueDidChange(){

    guard  let mySwitch = switchControl else { return }

    if mySwitch.isOn {

        header?.onlineOfflineStatusLabel.text = "on"
    }
    else {
        header?.onlineOfflineStatusLabel.text = "off"

    }

    self.header?.reloadInputViews()
    self.collectionView?.reloadData()

}

1 个答案:

答案 0 :(得分:0)

试试这个:

func setLeftNavButton() {

        let switchControl = UISwitch()
        switchControl.addTarget(self, action: #selector(switchValueDidChange(_:)), for: .valueChanged)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: switchControl)

        self.switchControl = switchControl

 }

 @objc
 func switchValueDidChange(_ sender: UISwitch){

        if sender.isOn {
            header?.onlineOfflineStatusLabel.text = "on"
        } else {
            header?.onlineOfflineStatusLabel.text = "off"
        }

        self.header?.reloadInputViews()
        self.collectionView?.reloadData()

}