swift - 当导航栏中的 UI 开关更改时更改标题中的标签

标签 swift xcode

我想更改 header 中的标签以与我的 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()

}

最佳答案

试试这个:

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()

}

关于swift - 当导航栏中的 UI 开关更改时更改标题中的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46990203/

相关文章:

xcode - mac 在重新安装 xcode 时卡住了?

ios - UITextFieldViewModeWhileEditing 更改我的 TextField 框架

swift - Swift 中的@selector()?

ios - 如何在 AppDelegate 中包含 NSPersistentContainer

json - 检索 Json 数据 - 如何?

swift - 无法在 Swift 中进行 Realm 迁移

objective-c - 在 Xcode 中查看 NSData 内容

iphone - iPhone 应用程序的财务图表

iOS tableView 单元格缓存问题未加载每个单元格

ios - swift :didSelectRowAtIndexPath