cfischer
cfischer

Reputation: 24912

Adding a UISwitch to a UINavigationItem

I want to have a UISwitch in the right corner of a UINavigationItem, instead of a UIBarButton. Is this possible without subclassing the UINavigationItem?

Upvotes: 4

Views: 2450

Answers (6)

Lahiru Pinto
Lahiru Pinto

Reputation: 1681

Swift Version

let customSwitch = UIBarButtonItem(customView: UISwitch())
navigationItem.rightBarButtonItem = customSwitch

Do this in viewDidLoad

Upvotes: 0

coders
coders

Reputation: 2477

For swift 4:

@IBOutlet weak var hostGuestSwitchOutletDeclare: UISwitch!
private func loadHostGuestSwitch(){
    hostGuestSwitchOutletDeclare.isOn = true
    hostGuestSwitchOutletDeclare.setOn(true, animated: false)
    hostGuestSwitchOutletDeclare.addTarget(self, action: #selector(switchValueDidChange), for: .valueChanged)
    if self.hostGuestSwitchOutletDeclare.isOn {
        self.navigationItem.title = "ON"
    } else {
        self.navigationItem.title = "OFF"
    }
}
@objc func switchValueDidChange(sender:UISwitch!) {
    if (sender.isOn == true){
        self.navigationItem.title = "ON"
    } else {
        self.navigationItem.title = "OF"
    }
}

Upvotes: 0

Swift Developer
Swift Developer

Reputation: 247

In Swift-

Write this code in viewDidLoad()

let switchDemo=UISwitch(frame:CGRectMake(15, 15, 0, 0))
        switchDemo.on = true
        switchDemo.setOn(true, animated: false)
        switchDemo.addTarget(self, action: "switchValueDidChange:", forControlEvents: .ValueChanged)
        self.view.addSubview(switchDemo)

And this is your func -

func switchValueDidChange(sender:UISwitch!)
{
if (sender.on == true){
println(“on”)
}
else{
println(“off”)
}
}

Upvotes: 2

Nag_iphone
Nag_iphone

Reputation: 967

It is possible with [UIBarButtonItem initWithCustomView:]:

self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView: mySwitch];

Upvotes: 1

proxi
proxi

Reputation: 1263

It is possible with [UIBarButtonItem initWithCustomView:]:

UISwitch* switchView = [[UISwitch alloc] init];
UIBarButtonItem* switchItem = [[UIBarButtonItem alloc] initWithCustomView:switchView];
self.navigationItem.rightBarButtonItem = switchItem;

Upvotes: 3

Mike Weller
Mike Weller

Reputation: 45598

You can create a UIBarButtonItem with a custom view inside it by using the initWithCustomView: method. For example:

UISwitch *switch = ...;
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:mySwitch];

Set this as the left/right item on your UINavigationItem.

Upvotes: 7

Related Questions