将UISwitch切换为BarButtonItem

时间:2016-03-23 12:45:34

标签: swift

我有一个开关作为条形按钮,但我不知道如何引用条形按钮项目的开/关值。除了条形按钮项目之外,XCode不允许将开关识别为其他任何内容。该开关嵌入在按钮中,无法引用。

@IBOutlet weak var toggleOutlet: UIBarButtonItem!
@IBAction func toggleButton(sender: UIBarButtonItem) {

   // if toggleOutlet.on // not recognized as bar button item

如果有人能提供帮助那就太棒了 感谢

4 个答案:

答案 0 :(得分:6)

感谢您的查询。

您可以使用以下步骤执行此操作。

在视图中加载,调用 setRightNavButton()并执行添加任务,

更新为Swift 4.1:

func audioSwitch(){
    let switchControl = UISwitch(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 50, height: 30)))
    switchControl.isOn = true
    switchControl.onTintColor = UIColor.white
    switchControl.setOn(true, animated: false)
    switchControl.addTarget(self, action: #selector(ViewController.switchValueDidChange(sender:)), for: .valueChanged)
    self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: switchControl)
}

@objc func switchValueDidChange(sender: UISwitch!)
{
    if sender.isOn {
        print("on")
    } else{
        print("off")
    }
}

答案 1 :(得分:1)

您可以在Swift 4.1中执行此操作,如:

func rightNavButton(){

    let frameSize = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 50, height: 30))
    let customSwitch = UISwitch(frame: frameSize)

    customSwitch.isOn = true
    customSwitch.onTintColor = UIColor.white
    customSwitch.setOn(true, animated: true)

    customSwitch.addTarget(self, action: #selector(ViewController.switchTarget(sender:)), for: .valueChanged)
    self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: customSwitch)
}


@objc func switchTarget(sender: UISwitch!)
{
    if sender.isOn {
        // do something ..
    } else{
        // do something ..
    }
}

答案 2 :(得分:0)

越来越近..但功能未被识别; [

@IBAction func togglePresence(sender: UIBarButtonItem) {
    updateSwitch()
}

// hold empty status of switch
// this is set to true during viewDidLoad
var statusofswitch:Bool!

func updateSwitch() {
    if statusofswitch == true {
        statusofswitch = false
    }
    if statusofswitch == false {
        statusofswitch = true
    }
}

答案 3 :(得分:0)

使用更多按钮切换UISwitch作为 Swift 4

中的BarButtonItem
let switchControl = UISwitch(frame: CGRect(x:0, y:0, width:35, height:35))        
switchControl.onTintColor = UIColor.red
switchControl.setOn(true, animated: false)
switchControl.addTarget(self, action: #selector(switchTapped(sender:)), for: .valueChanged)

let someImage = UIImage(named: "imageName")!
let someButton = UIBarButtonItem(image: someImage,  style: .plain, target: self, action: #selector(someButtonTapped(sender:)))

self.navigationItem.rightBarButtonItems = [UIBarButtonItem.init(customView: switchControl),someButton]

动作

@objc func switchTapped(sender: UIBarButtonItem) {}
@objc func someButtonTapped(sender: UIBarButtonItem) {}