将UISwitch添加到UINavigationItem

问题描述 投票:4回答:5

我想在UINavigationItem的右上角有一个UISwitch,而不是UIBarButton。如果没有子类化UINavigationItem,这可能吗?

objective-c cocoa-touch uibarbuttonitem uinavigationitem uiswitch
5个回答
7
投票

您可以使用UIBarButtonItem方法在其中创建带有自定义视图的initWithCustomView:。例如:

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

将其设置为UINavigationItem上的左/右项。


3
投票

有可能与[UIBarButtonItem initWithCustomView:]

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

2
投票

在Swift-

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

这是你的功能 -

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

1
投票

有可能与[UIBarButtonItem initWithCustomView:]

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

0
投票

对于快速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"
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.