我有两个ViewController,FirstViewController和SecondViewController。 在SecondViewController上有UISlider。在FirstViewController上有一个警报。
现在我要传输UISlider值,该值是要在FirstViewController上报警的音量。
ps。我要设置的功能与默认的iPhone设置滑块完全相同。
我会很高兴,所以请你们把我的知识告诉我。
import UIKit
import AVFoundation
class FirstViewController: UIViewController, AVAudioPlayerDelegate,
UITableViewDelegate, UITableViewDataSource{
let TODO = ["A", "B", "C"]
let notificationCenter = NotificationCenter.default
var volume = Float()
var counter = 0
var timer = Timer()
var startTime:Double = 0.0
var audioPlayer: AVAudioPlayer!
@IBOutlet weak var tableView: UITableView!
@IBAction func firstSwitch(_ sender: UISwitch)
{
if (sender).isOn
{
timer = Timer.scheduledTimer(withTimeInterval: 1 * 1, repeats: false, block: { timer in
self.audioPlayer.play()
self.audioPlayer.numberOfLoops = -1
print(self.audioPlayer.isPlaying)
})
}else{
timer.invalidate()
print("switch1stopped")
self.audioPlayer.stop()
}
}
notificationCenter.addObserver(self, selector: #selector(catchNotification(notification:)), name: NSNotification.Name(rawValue: "test"), object: nil)
}
@objc func catchNotification(notification: Notification) -> Void {
print("Catch notification")
audioPlayer.volume = volumeChane.value
//Use of unresolved identifier 'volumeChane'
}
///////////////////////////////////////////////// /////////////////////////
import UIKit
import AVFoundation
class SecondViewController: UIViewController {
var audioPlayer: AVAudioPlayer!
let notificationCenter = NotificationCenter.default
@IBOutlet weak var volumeSlider: UISlider!
@IBOutlet weak var volumeLabel: UILabel!
@IBAction func volumeChange(_ sender: UISlider)
{
volumeLabel.text = String(Int(sender.value))
volumeSlider.value = sender.value
audioPlayer.volume = volumeSlider.value
notificationCenter.post(name: NSNotification.Name(rawValue: "test"), object: nil)
audioPlayer.play()
}
override func viewDidLoad()
{
super.viewDidLoad()
if let url=Bundle.main.url(forResource:"Alarm",withExtension:".mp3" )
{
do {
audioPlayer = try AVAudioPlayer(contentsOf:url)
audioPlayer?.play(atTime:1 * 10)
}catch{
audioPlayer = nil
}
}else{
fatalError("Url is nil")
}
}
extension Notification.Name
{
static let myNotificationName = Notification.Name("test")
}
答案 0 :(得分:0)
将NSNotificationCenter
用于诸如此类的简单任务可能会过大。通常,您可以使用闭包来捕获组件或视图控制器中的数据更改。
在SecondViewController
中创建一个包含闭包的变量:
var onVolumeChange: ((value: Float) -> Void)?
在IBAction
中调用它,它监视滑块的onChange事件。
@IBAction func volumeChange(_ sender: UISlider)
{
self.onVolumeChange?(sender.value)
}
在导航到第二个时,从onVolumeChange
中传递FirstViewController
闭包。我不确定您如何执行导航,所以我假设您以编程方式进行导航。
let vc = UIStoryboard(name: "main", bundle: nil).instantiateViewController(withIdentifier: "SecondViewController")
vc.onVolumeChange = { value in
audioPlayer.volume = value
}
self.navigationController?.pushViewController(vc, animated: true)