我想在UINavigationItem的右上角有一个UISwitch,而不是UIBarButton。如果没有子类化UINavigationItem,这可能吗?
您可以使用UIBarButtonItem
方法在其中创建带有自定义视图的initWithCustomView:
。例如:
UISwitch *switch = ...;
UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:mySwitch];
将其设置为UINavigationItem
上的左/右项。
有可能与[UIBarButtonItem initWithCustomView:]
:
UISwitch* switchView = [[UISwitch alloc] init];
UIBarButtonItem* switchItem = [[UIBarButtonItem alloc] initWithCustomView:switchView];
self.navigationItem.rightBarButtonItem = switchItem;
在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”)
}
}
有可能与[UIBarButtonItem initWithCustomView:]
:
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView: mySwitch];
对于快速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"
}
}